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

asp.net-mvc entity-framework jquery model-binding razor

Question

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" />

1
13
1/16/2013 9:14:45 PM

Accepted Answer

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.

31
1/16/2013 7:50:22 AM

Popular Answer

Just give it a name:

<input type="text" name="foo" />

and then inside your controller action simply have an argument with the same name:

public ActionResult Process(string foo)
{
    // The foo argument will contain the value entered in the 
    // corresponding input field
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow