Model Binding in ASP.NET Core MVC

SPONSOR AD

Model Binding in ASP.NET Core MVC

I will discuss Model Binding in ASP.NET Core MVC Applications in this article. Please read our previous article discussing Tag Helpers in ASP.NET Core MVC.

What is Model Binding in ASP.NET Core?

The Model Binding is a mechanism in the ASP.NET Core Application that extracts the data from an HTTP request and provides them to the controller action method parameters. The action method parameters may be simple types like integers, strings, etc., or complex types such as Student, Order, Product, etc.

Example Without Using Model Binding in ASP.NET Core MVC

Let us first understand, without using Model Binding, how we can capture the request data using FormCollection in the ASP.NET Core MVC Application. In ASP.NET Core MVC, FormCollection is a method to retrieve form data from HTTP requests.

So, first, create a new ASP.NET Core MVC Application with the name ModelBindingDemo. Then, modify the Home Controller as follows. As you can see, we are using FormCollection as a parameter to capture the form data within the controller action method.

SPONSOR AD
using Microsoft.AspNetCore.Mvc;
namespace ModelBindingDemo.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public string SubmitForm(IFormCollection form)
        {
            var UserName = form["UserName"].ToString();
            var UserEmail = form["UserEmail"].ToString();

            // Handle data as needed...
            return $"User Created: UserName: {UserName}, UserEmail: {UserEmail}";
        }
    }
}

Next, modify the Index.cshtml view as follows:

@{
    ViewData["Title"] = "Home Page";
}

<form method="post" asp-controller="Home" asp-action="SubmitForm">
    <label>Name:</label>
    <input type="text" name="UserName" />
    <br />

    <label>Email:</label>
    <input type="text" name="UserEmail" />
    <br />

    <button type="submit">Submit</button>
</form>
Pros and Cons of Using FormCollection:
Pros:
  • Flexible: It allows you to dynamically handle form submissions when you don’t have a pre-defined model.
Cons:
  • Less Type Safety: Errors related to type mismatches or missing fields might only be detected at runtime.
  • No Model Validation: You must manually handle validation and error messages.
  • Less Intuitive: Strongly typed model binding is more readable and works better with tools like IntelliSense.

Note: While model binding using strongly typed views is more popular due to its advantages in type safety, error handling, and IntelliSense support, FormCollection can be used in scenarios where the model isn’t known at compile time or for other reasons.

We can rewrite the previous example very easily using Model binding. So, let us first create a model to hold the UserName and UserEmail. So, create a class file with the name User.cs within the Models folder and copy and paste the following code.

using System.ComponentModel.DataAnnotations;
namespace ModelBindingDemo.Models
{
    public class User
    {
        [Required]
        public string UserName { get; set; }
        [Required]
        public string UserEmail { get; set; }
    }
}

Next, modify the Index.cshtml view as follows:

@model User
@{
    ViewData["Title"] = "Home Page";
}

<form method="post" asp-controller="Home" asp-action="SubmitForm">
    <label>Name:</label>
    <input asp-for="UserName" />
    <br />

    <label>Email:</label>
    <input asp-for="UserEmail" />
    <br />

    <button type="submit">Submit</button>
</form>

Next, modify the Home Controller as follows:

using Microsoft.AspNetCore.Mvc;
using ModelBindingDemo.Models;

namespace ModelBindingDemo.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public string SubmitForm(User user)
        {
            if (user != null)
            {
                if (ModelState.IsValid)
                {
                    // Handle data as needed...
                    return $"User Created: UserName: {user.UserName}, UserEmail: {user.UserEmail}";
                }
            }
            return "Some Error Occured";
        }
    }
}

Now, let us proceed and understand Model Binding in detail.

What is Model binding in ASP.NET Core MVC?

Model binding in ASP.NET Core MVC is a mechanism that maps client request data (like form values, route data, query string parameters, request body, and HTTP headers) to action method parameters. This allows us to work directly with strongly typed .NET objects in our action methods. This will eliminate the need to manually parse and convert the raw HTTP request data to .NET objects in the ASP.NET Core MVC Application.

SPONSOR AD
Why Is Model Binding Important in ASP.NET Core MVC?

The Model Binding Is Important in ASP.NET Core MVC because of the following.

  • Type Safety: Model binding converts client data into .NET types, ensuring that our action methods’ values are already of the expected data type. This will reduce the need for manual data type conversions and associated error checks.
  • Automatic Validation: Model binding can validate the incoming data against predefined rules when combined with data annotations. We can easily check if the data is valid by examining the ModelState.IsValid property. How to use ModelState.IsValid property will be discussed in detail in our upcoming articles.
  • Code Simplification: Model binding eliminates the repetitive code of manually extracting values from the request and converting them to .NET types.
How Model Binding Works in ASP.NET Core MVC?

The Model Binding Works in ASP.NET Core MVC as follows:

  • Parameter Names and Source: The model binder looks for data in the request that matches the names of the action method’s parameters. Depending on the source attribute (e.g., [FromQuery], [FromBody], [FromRoute]), it knows where to look, such as in the query string, the request body, or the route data.
  • Type Conversion: The model binder converts the data to the parameter’s type once a match is found. For instance, a string from the query string can be converted to an integer if the action method expects an integer parameter.
  • Data Validation: If the model is decorated with validation attributes (like [Required], [Range], [MaxLength], [MinLength] Data Annotation Attributes), the model binder will also validate the data after binding it. The results of the validation are stored in the ModelState.
Different Model Binding Techniques in ASP.NET Core MVC:
1. Basic Model Binding:

ASP.NET Core MVC tries to bind request data to the action method parameters by name.

public IActionResult Register(string username, string password) 
{ 
    //... 
}

In the above example, if the HTTP request has a form or query string with username and password, those will be automatically bound to the method parameters.

2. Attribute Routing:

Model binding can bind data from the URL using attribute routing.

[Route("product/{id}")]
public IActionResult ProductDetails(int id) 
{ 
    //... 
}
3. FromBody:

The [FromBody] attribute indicates that a parameter should be deserialized from the request body, typically in the format of JSON or XML.

[HttpPost]
public IActionResult Create([FromBody] Product product) 
{ 
    //... 
}
4. FromForm:

The [FromForm] attribute binds data from form fields in a form submit action.

[HttpPost]
public IActionResult Register([FromForm] UserRegistrationModel user) 
{ 
    //... 
}
5. FromQuery:

The [FromQuery] attribute binds parameters from the query string.

SPONSOR AD
public IActionResult Search([FromQuery] string query) 
{ 
    //... 
}
6. FromRoute:

The [FromRoute] attribute binds parameters from the route data.

[HttpGet("{id}")]
public IActionResult Get(int id) 
{ 
    //... 
}
7. FromHeader:

The [FromHeader] attribute binds a parameter from an HTTP header.

public IActionResult CheckUserAgent([FromHeader(Name = "User-Agent")] string userAgent) 
{ 
    //... 
}
8. Complex Type Binding:

ASP.NET Core MVC can bind complex types by recursively binding properties of the complex type. For instance, if you submit a form with the fields Product.Name and Product.Price, they can be bound to a complex object:

public IActionResult Create(Product product) 
{ 
    //... 
}
9. Custom Model Binding:

In scenarios where the default model binding behavior isn’t adequate, you can implement custom model binders by inheriting from interfaces like IModelBinder.

Points to Remember:
  • Naming the form fields, query string parameters, or route values is crucial. They should match the names of the action method’s parameters for model binding to work correctly.
  • Always validate the data after model binding using the ModelState.IsValid property. This ensures that the data conforms to the expected format and rules.
  • Be wary of over-posting. Do not blindly bind client data directly to your database models, as this can expose your application to vulnerabilities. Use ViewModels or DTOs (Data Transfer Objects) to protect against this.

So, model binding in ASP.NET Core MVC provides a powerful and efficient way to handle client request data, ensuring developers can focus on application logic rather than the intricacies of parsing HTTP requests.

In the next article, I will discuss Using FromForm to Perform Model Binding in ASP.NET Core MVC with Examples. In this article, I try to explain the basic concepts of Model Binding. I hope you enjoy this Model Binding in ASP.NET Core MVC article.

SPONSOR AD

9 thoughts on “Model Binding in ASP.NET Core MVC”

  1. Its a greattt tutorial …but so many things also we are expecting ..Please provide the continuation of this technology

Leave a Reply

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