TOC

This article is currently in the process of being translated into Vietnamese (~39% done).

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!");
}

Form sẽ gửi dữ liệu tới phương thức và gán nó cho các đối tượng. Tuy nhiên, ASP.NET MVC với Model Binding, View sẽ dùng dữ liệu từ Model để tạo ra ví dụ Form để thay đổi dữ liệu trong Model. Phương thức trong Controller sẽ xử lý dữ liệu đưa lên như đối tượng của Model thay vì việc ta phải tự đọc chuỗi từ FORM. Hay nói cách khác, nhờ có Model Binding mà giao tiếp giữa client và server bằng các object.

Using Model Binding

Đầu tiên, ta cần một Model đơn giản như sau:

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

Trong Controller, chúng ta truyền một đối tượng của class này vào View. Trong thực tế, chúng ta có thể lấy WebUser từ cơ sở dữ liệu nhưng để đơn giản cho việc minh họa thì ta làm như sau:

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

View sẽ biết được loại Model với khai báo @model, chúng ta có thể dùng phương thức helper xây dựng 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" />
}

Kết quả ta có như sau với label và textbox để nhập thông tin cho 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!