What is model binding in ASP.NET MVC?

Model-View-Controller (MVC) is a web application framework developed by Microsoft that offers a powerful feature known as model binding. This feature simplifies passing data between the user interface and the controller in MVC applications. Model binding automatically maps incoming data from various sources to the parameters of controller action methods, making it easier for developers to handle user input and interact with the application’s models.

Types of model binding

The types of model binding are:

  • Simple type bonding: Simple types such as strings, integers, and other types can be bound directly from the request data.

  • Complex type bonding: Complex types are custom objects with multiple properties. For instance, consider a User class with properties like Name and Email. We can bind such complex types to action parameters.

Mechanism of model binding

The model binding mechanism is as follows:

  • Route resolution: When a request is made to the MVC application, the routing engine determines which controller and action method should handle the request based on the URL and configured routes in the application.

  • Parameter discovery: This process inspects the method signature after route resolution to determine its parameters, which can include simple types, complex types, or collections.

  • Forming a binding context: This creates a binding context for the current request, which contains information about the HTTP request, including form data, query string parameters, route data, and other contextual information.

  • Parameter matching: Model binding matches the parameters of the action method with the available data in the binding context.

  • Value conversion: It converts the raw string data into the appropriate data type once a match is found. In the case of complex types, it matches each property name with the corresponding field name or query string parameter to populate the object’s properties.

  • Invoking the action method: It invokes the action method once the model binding is complete. The action method can then process the data and generate an appropriate response.

Example

Consider an example where a user submits a registration form to register. The form contains fields such as First Name, Last Name, and Age, which will bind to the parameters of the action method in the controller. The diagram representation of this scenario is shown below:

Registration Form
Registration Form
1 of 7

Let’s create a UserModel class for these data:

public class UserModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
}

This class defines a user data structure for registration purposes. It includes properties for FirstName, LastName, and Age. Each property is annotated with the [Required] attribute, indicating that the user must fill out these fields. Additionally, the [Display] attribute specifies the user-friendly names for these fields, enhancing readability.

Now, let’s add the Register method to the controller:

[HttpPost]
public IActionResult Register(UserModel user)
{
if (ModelState.IsValid)
{
// For example purposes, just return a view with the user details
return View("RegistrationSuccess", user);
}
// If model validation fails, return to the registration form with error messages
return View("Index", user);
}

When the form is submitted, the values from the form fields will bind to the parameters of the Register action based on their names. For instance, the value entered in the First Name field will be assigned to the user.FirstName parameter, the value of the Last Name field to the user.LastName parameter, and Age field will be assigned to the user.Age parameter.

The final code is as below:

cd /usercode/ModelBinding/wwwroot;
clear;
git clone https://github.com/RabiaNoumanSiddiq/lib.git;
clear;
cd ..;
clear;
dotnet build;
clear;
dotnet run --launch-profile https;
Model binding in registration form

Conclusion

In conclusion, the model binding feature simplifies data interaction between the user interface and controller by automatically mapping incoming data to controller action parameters. Understanding the types and mechanisms of model binding helps efficiently manage form submissions and enhances user experience.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved