Tuesday, 19 May 2015

ASP.NET MVC Custom Model Binding

 Model binding is ASP.NET MVC's mechanism for mapping HTTP request data directly into action method parameters and custom .Net objects. Each time your application receives an HTTP request containing the form's data as a pair of key/value pairs, the ControllerActionInvoker invokes the DefaultModelBinder to transform that raw HTTP request into something more meaningful to you, which would be a .Net object. This just works and I love it.
We know that if the model property matches exactly with view, then MVC architecture automatically takes care of the model binding process. This is very simple and straight forward.

But, if the model property is not matched exactly with the view? Then how do we bind model in time of data submission?

In this post, we will understand how to bind model when model property is incompatible with View. To implement our custom model binding mechanism, we have to implement either IModelBinder interface in our custom class or we can derive our custom class from DefaultModelBinder class.

The DefaultModelBinder class implements the IModelBinder interface. So, let’s see the definition of IModelBinder. It contains only one method called BindModel and it takes two parameters; one is ControllerContext and the other is ModelBindingContext. Have a look at the below definition of IModelBinder.

public interface IModelBinder
    {
        // Summary:
        //     Binds the model to a value by using the specified controller context and
        //     binding context.
        //
        // Parameters:
        //   controllerContext:
        //     The controller context.
        //
        //   bindingContext:
        //     The binding context.
        //
        // Returns:
        //     The bound value.
        object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);

    }

Now, let’s look at the definition of DefaultModelBinder class. The class contains many methods including BindMode() method. Have a look at the below screen, though it’s not full class definition. The BindModel() method is defined as virtual method which means we can implement the method in our own way.



Ok, let’s try to implement our custom model binding mechanism; first we will implement IModelBinder class in our custom binder class.

So, let’s create one simple model class called Person and it contains only two properties. The first property is name which will be a combination of three different properties called “first_name” ,”middle_name” and “last_name” that we will define in view.

namespace ModelBinder.Models
{
    public class Person
    {
        [Required]
        [MaxLength(50, ErrorMessage = "Full name should be within 50 character")]
        public string full_name { get; set; }

        [Range(18, 80)]
        [Required(ErrorMessage = "Please provide age")]
        public Int32 Age { get; set; }
    }

}

Here is the view which will be mapped with the Person mode. We are seeing that there are three different properties which will construct the full name.

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
            @{Html.BeginForm("PostData", "Customodelbinder");
                <table>
                    <tr>
                        <td>First Name : </td>
                        <td>@Html.TextBox("first_name")</td>
                    </tr>
                    <tr>
                        <td>Middle Name : </td>
                        <td>@Html.TextBox("middle_name")</td>
                    </tr>
                    <tr>
                        <td>Surname :</td>
                        <td> @Html.TextBox("last_name")</td>
                    </tr>
                    <tr>
                        <td>Age:</td>
                        <td> @Html.TextBox("age") </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <input type="submit" name="Save" value="Save" />
                        </td>
                    </tr>
                </table>
            }
    </div>
</body>

</html>

Now, the fact is clear that the property of model is not mapped with property of View, then we have to write our own mapping logic to bind the view data in model.

Create one class and implement IModelBinder interface within it. In the below snippet, we have created “PersonModelBinder” custom binding class and implemented IModelBinder interface. We have seen that IModelBinder contains only one method called BindModel and we have implemented the logic to map view property with the model property.

public class PersonModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;

        string first_name = request.Form.Get("first_name");
        string middle_name = request.Form.Get("middle_name");
        string last_name = request.Form.Get("last_name");
        int Age = Convert.ToInt32(request.Form.Get("age"));
        return new Person { full_name = first_name + middle_name + last_name, Age = Age };
    }

}

The implementation is very simple, just we are combining first_name, middle_name and last_name to combine full name and returning Person object accordingly. Fine, now we will create the controller which will contain PostData() action and as parameter, it will take Person type object after binding in our custom PersonModelBinder class. Here is the simple implementation.

public class CustomodelbinderController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public void PostData([ModelBinder(typeof(PersonModelBinder))] Person person)
    {

    }

}

Now, we have to register the custom binder class in MVC pipeline. Just add the below line in global.asax page.

//Register Custom Model binder

ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());

Fine, we have setup everything to bind model using our custom class. Let’s run the application and we should see the below view.

I have given few arbitrary data and in controller we are seeing that the first_name, middle_name and last_name property have combined within single property called full_name.


Now, as we said, we can use DefaultModelBinder class too to implement BindModel method, Just we have to override the method. Here is the sample implementation.

public class PersonModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;

        string first_name = request.Form.Get("first_name");
        string middle_name = request.Form.Get("middle_name");
        string last_name = request.Form.Get("last_name");
        int Age = Convert.ToInt32(request.Form.Get("age"));
        return new Person { full_name = first_name + middle_name + last_name, Age = Age };
    }
}

One more usefull link is : Click here

ControllerActionInvoker - Represents a class that is responsible for invoking the action methods of a controller.
Syntax: public class ControllerActionInvoker : IActionInvoker

DefaultModelBinder - Maps a browser request to a data object. This class provides a concrete implementation of a model binder.
Syntax: public class DefaultModelBinder : IModelBinder

In this tip, we have learned to implement custom model binding when model property is not matched with the view. Hope it will help you to understand custom model binding.

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (9) Web Service (1) XMl (1)