Model Binding in Asp.Net MVC

Model binding is an elegant bridge between the HTTP request and the C# methods that define our actions methods.

Suppose someone requested for URL  “/Home/Index/1” which mean that filter the data by index 1 in controller method.

The process by which the URL segment was converted into the int method argument is an example
of model binding.

  • Model binders are defined by the IModelBinder interface

We can defined custom model binders, but most developer rely on built-in model binder.  Below are four inbuilt model binder.

  • Request.Form : Values provided by the user in HTML form elements.
  • RouteData.Values : The values obtained using the application routes.
  • Request.QueryString  :Data included in the query string portion of the request URL.
  • Request.Files : Files that have been uploaded as part of the request.

The searching order of default model binder for empid parameter is as follows. The search is stopped as soon as a value is found.

1. Request.Form[“empid”]
2. RouteData.Values[“empid”]
3. Request.QueryString[“empid”]
4. Request.Files[“empid”]

“It is important that the parameters for your action method match the data property you are looking for.”

If we pass url like Home/index/Test, it will try to convert Test into int which leads to throw and exception.  so we may add to controller a default value so whenever the model binder is unable to find a value for the id parameter it will display default value.

Source                                 IValueProvider Implementation

  • Request.Form                      FormValueProvider
  • RouteData.Values               RouteDataValueProvider
  • Request.QueryString         QueryStringValueProvider
  • Request.Files                       HttpFileCollectionValueProvider

Restricting the Binder Data Source

The FormCollection class implements the IValueProvider interface, and if we define the action
method to take a parameter of this type, the model binder will provide us with an object that we can pass
directly to the UpdateModel method.

When model binding is invoked automatically, binding errors are not signaled with exceptions. Instead, we must check the result through the ModelState.IsValid property.