ASP.NET MVC: How to 'model bind' a non html-helper element

dan picture dan · Jan 16, 2013 · Viewed 27.8k times · Source

Could you tell me a way(s) that I can bind a model property to a html-element, created without using html helper?

In other words to a plain html element such as: <input type="text" />

Answer

moribvndvs picture moribvndvs · Jan 16, 2013

If you are referring to Model Binding, it does not require helpers, but naming convention. Helpers just make it easy and concise to create the HTML markup.

You could create plain HTML inputs and just set the name attribute correctly. The default naming convention is just dot based, omitting the parent level entity's name, but qualifying it from there.

Consider this controller:

public class MyControllerController : Controller
{
     public ActionResult Submit()
     {
         return View(new MyViewModel());
     }

     [HttpPost]
     public ActionResult Submit(MyViewModel model)
     {
            // model should be not null, with properties properly initialized from form values
            return View(model);
     }
}

And this model:

public class MyNestedViewModel
{
    public string AnotherProperty { get; set; }
}

public class MyViewModel
{
    public MyViewModel()
    {
         Nested = new MyNestedViewModel();
    }

    public string SomeProperty { get; set; }

    public MyNestedViewModel Nested  { get; set; }
}

You could create the following form purely in HTML:

<form method="POST" action="MyController/Submit">
    <div><label>Some property</label><input type="text" name="SomeProperty" /></div>
    <div><label>Another property</label><input type="text" name="Nested.AnotherProperty" /></div>
    <button type="submit">Submit</button>
</form>

If you want to display the posted values (in the second Submit overload), your HTML will have to be modified render the model properties. You'd place this in a view, in this case using Razor syntax and called Submit.cshtml:

@model MyViewModel
<form method="POST" action="MyController/Submit">
    <div><label>Some property</label><input type="text" name="SomeProperty" value="@Model.SomeProperty" /></div>
    <div><label>Another property</label><input type="text" name="Nested.AnotherProperty" value="@Model.Nested.SomeProperty" /></div>
    <button type="submit">Submit</button>
</form>

So, this can be done without helpers, but you'd want to use them as much as possible.