Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a form from a model in ASP.NET MVC 5?

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.

like image 811
Mankind1023 Avatar asked Mar 03 '15 22:03

Mankind1023


2 Answers

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)
like image 116
Sam Avatar answered Sep 22 '22 16:09

Sam


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?

like image 45
Mankind1023 Avatar answered Sep 19 '22 16:09

Mankind1023