What is .NET MVC model binding

Model binding is the part of the framework that takes an input from a HTML form (or other formats) and converts it into an object in code. So that if you have this HTML form:

<form method="post" action="/BindModel">
  <input type="text" name="UserText" />
  <input type="text" name="UserNumber" />
  <input type="submit" value="Send" />

When you click the Send button, it will send whatever has been put into the input fields to the server, at the URL “/BindModel”. On the server side, in code, you have a simple class:

public class UserData {
  public String UserText { get; set; }
  public int UserNumber { get; set; }

Model binding lets you define an action like this:

public ActionResult BindModel(UserData input) {
  // code here

When the BindModel method is executed in response to clicking the Send button, model binding takes the contents of the form and copies the values over to the object (function argument) “input”. There will even be an error if the user entered something that isn’t a number in the second field, because the UserData class specifies that UserNumber is of “int” data type.

There is, of course, much more to it, but this is the core.

One thought on “What is .NET MVC model binding

  1. Pingback: Why are you wishing cancer on me? | MoDo:Emuārs

Leave a Reply

Your email address will not be published. Required fields are marked *