TOC
Models:

Model Binding

Communication between a client (usually a browser) and the web server is very simple - strings are passed back and forth, because the client doesn't have any understanding of your fancy .NET objects. So, back in the old days of ASP Classic and ASP.NET WebForms, before the MVC framework was introduced into the .NET framework, the process of updating a Model was a bit cumbersome. First, you would have to create a FORM with all the fields that the user could change. When this FORM was posted back to the server, you would have to read each of the FORM fields and assign it to your Model. If we were to take this approach and use it with ASP.NET MVC, it would look something like this:

<form method="post" action="/ModelBinding/UpdateFromOldSchoolForm">
    <input type="text" name="txtFirstName" value="@Model.FirstName" />
    <input type="text" name="txtLastName" value="@Model.LastName" />
    <input type="submit" value="Update" />
</form>
public IActionResult UpdateFromOldSchoolForm()
{
    WebUser webUser = LoadUserFromDatabase();

    webUser.FirstName = Request.Form["txtFirstName"];
    webUser.LastName = Request.Form["txtLastName"];

    UpdateUserInDatabase(webUser);

    return Content("User updated!");
}

A manually constructed FORM, which will POST the values to a method, which will then read the values and assign it to an object. All very basic and oldschool. However, with ASP.NET MVC, the concept of Model Binding was introduced. It allows your Views to use information from the Model to generate e.g. a FORM for editing the Model, but even more helpful, that allows the receiving method on the Controller to treat the posted values as an object of the Models type, instead of forcing you to read strings from the FORM. In other words, you can now keep working with objects all the way through the communication between client and server, thanks to the magic of Model Binding. Let's see how it works!

Using Model Binding

First, we need a Model. If you don't know what the Model is, I suggest that you skip a few articles back and read up on it. We'll create a simple Model (class) for handling information about a user:

public class WebUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

In our Controller, we can now pass an instance of this class to the View. In a real-world application, we would probably get the WebUser object from a database, but to keep things simple, we just generate a new one for this demonstration:

[HttpGet]
public IActionResult SimpleBinding()  
{  
    return View(new WebUser() { FirstName = "John", LastName = "Doe" });  
}

By letting our View know what kind of Model it can expect, with the @model directive, we can now use various helper methods (more about those later) to help with the generation of a FORM:

@using(var form = Html.BeginForm())
{
    <div>
@Html.LabelFor(m => m.FirstName)
@Html.TextBoxFor(m => m.FirstName)
    </div>

    <div>
@Html.LabelFor(m => m.LastName)
@Html.TextBoxFor(m => m.LastName)
    </div>

    <input type="submit" value="Submit" />
}

The result will be a very generic-looking FORM, but with labels and textboxes designated to host the properties of your Model:

By default, the FORM will be posted back to the same URL that delivered it, so to handle that, we need a POST-accepting Controller method to handle the FORM submission:

[HttpPost]
public IActionResult SimpleBinding(WebUser webUser)
{
    //TODO: Update in DB here...
    return Content($"User {webUser.FirstName} updated!");
}

Notice how our Controller action takes just one parameter, of the same type as the Model we passed into the View originally: The WebUser class. Behind the scenes, ASP.NET MVC will now process the FORM and assign the values found in its editable controls to the properties of the WebUser class. This is the magic of Model Binding!

Summary

Thanks to Model Binding, you can maintain relations between your Models and your Views much easier. In this article, we only scratched the surface though - there are a lot more possibilities with Model Binding, as you'll discover in some of the upcoming articles.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!