Is there a built in function that basically takes an object parameter from a model and creates a complete form based on that?
Currently I'm doing a line for each property:
@model AutomatedTellerMachine.Models.ContactFormModel
@using (Html.BeginForm())
{
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
<input type="text" name="name" class="form-control" />
@Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="text" name="phone" class="form-control" />
@Html.ValidationMessageFor(model => model.phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<textarea name="message" class="form-control"></textarea>
@Html.ValidationMessageFor(model => model.message, "", new { @class = "text-danger"})
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Send" class="btn btn-default"/>
</div>
</div>
</div>
}
I realize you can get Visual Studio to create everything for you, but I need to mix and match.
You can do this with Editor Templates. Create a new Razor view named ContactFormModel.cshtml
(the name must match the model). Inside that file, copy all of the code from your existing view.
You can use normal Razor syntax to render whatever HTML that you want to include when calling EditorFor()
on this model.
Then, you can have Razor render your custom template with:
@Html.EditorForModel(Model)
If you want to do the same for a specific object (e.g., YourObjectName
) in the model, rather than the whole thing, create a file named YourObjectName.cshtml
.
At the top of this file:
@model NameSpace.YourObjectName
Then use this in the outer view that you want to render the custom Editor Template in:
@Html.EditorFor(model => model.YourObjectPropertyName)
Ok so I figured it out, using:
@Html.EditorForModel(Model)
works, but is there a way to assign a class to all elements that it will create?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With