ASP.NET MVC Model Binding Form Inputs To Action Parameters

The conventions followed by asp.net mvc for model binding are volatile to my brain for some reason.

Here is a summary of the different ways to bind input fields to action parameters.
Assuming the following class:

public class Person
{
    public string Name;
    public string Email;
}

Binding a Custom type

<%= Html.TextBox("Name") %>
<%= Html.TextBox("Email") %>

Will bind to:

public ActionResult MyAction(Person myPerson)
{
    // …
}

Binding a Custom type with parameter name prefix

<%= Html.TextBox("myPerson.Name") %>
<%= Html.TextBox("myPerson.Email") %>

Will bind to:

public ActionResult MyAction(Person myPerson)
{
    //…
}

Binding a Custom type with a custom prefix

<%= Html.TextBox("myPrefix.Name") %>
<%= Html.TextBox("myPrefix.Email") %>

Will bind to:

public ActionResult MyAction([Bind(Prefix = "myPrefix")] Person myPerson)
{
    // ...
}

Binding to Collections of Simple Types

<%= Html.TextBox("Name") %>
<%= Html.TextBox("Name") %>
<%= Html.TextBox("Name") %>

Will bind to:

public ActionResult MyAction(List<string> Name)
{
    // …
}

Binding to Collections of Custom Types

<%= Html.TextBox("myPerson[0].Name") %>
<%= Html.TextBox("myPerson[0].Email") %>
<%= Html.TextBox("myPerson[1].Name") %>
<%= Html.TextBox("myPerson[1].Email") %>

Will bind to

public ActionResult MyAction(List<Person> myPerson)
{
    //…
}

Binding to Dictionary of Custom Types

<%= Html.Hidden("myPerson[0].key", "keyOne") %>
<%= Html.TextBox("myPerson[0].value.Name") %>
<%= Html.Hidden("myPerson[1].key", "keyTwo") %>
<%= Html.TextBox("myPerson[1].value.Name") %>

Will bind to

public ActionResult MyAction(IDictionary<string, Person> myPerson)
{
    // …
}

One Trackback

  1. By ASP.NET MVC Archived Blog Posts, Page 1 on September 7, 2009 at 4:04 AM

    [...] to VoteASP.NET MVC Model Binding Form Inputs To Action Parameters (9/3/2009)Thursday, September 03, 2009 from Marco MagdyThe conventions followed by asp.net mvc for model [...]

Post a Comment

Required fields are marked *

*
*