How To Implement Custom Model Binders In ASP.NET MVC?

Custom binder ASP.NET MVC

Custom Model in ASP.NET can be created using Entity Framework, ADO.NET code or other data access tactics. While working on ASP Dot NET development for building the Model layer, declare Plain Old CLR Objects (POCO). If you use Entity Framework, then the app provides POCO objects which you can use as entities. The MVC (Model-View-Controller) provides action techniques to access POCO objects as its input parameters and the action technique uses the CLR objects to save it to the database. 

ASP.NET MVC scaffolds Views using POCO. And the Model Binder comes into picture during the scaffolding process. The Model binder maps the View Elements to POCO model properties while the model binder acts as a bridge between the View and the MVC models.

Model Binder in ASP.NET MVC:
MVC utilizes following types for Model Binding:

IModelBinder interface - Defines the methods that are essential for a Model Binder, such as the BindModel method. It is responsible for binding a model to certain values with the help of ControllerContext and BindingContext.

IModelBinderProvider interface – This interface comprises methods that facilitate dynamic implementation of model binding for classes that implement the IModelBinder interface. This can be utilized for managing the custom binder for the data type posted by the end user in the Views.

DefaultModelBinder class

  • This class is utilized for mapping a browser request with a data object. It is a concrete request of the IModelBinder.
  • MVC utilizes this class by default to map the data sent by the View elements to the POCO properties in order to enable the controller to use it for further processing.

Steps To Implement Custom Model Binders:

Step 1 – Create a new ASP.NET web app and name it as MVC_CustomModelBinder and click OK. This will display a window where you need to select ‘Empty’ and ‘MCV’ checkbox.

Step 2 – Add a new SQL Server database and name it as ApplicationDB.mdf. Ensure you keep the database empty. Add a new ADP.NET Entity Data Model in the Models folder and name it as ApplicationEntities. And in the wizard, choose Code-First from the database. Now select the ApplicationDB.mdf and finish the Entity Data Model wizard. This will include ApplicationEntities.cs class file with ApplicationEntities class within. As this class is derived from DbContext class, you can use it to perform Database operations. 

Step 3 – Add a new class called Employee.cs  in the Models folder with the following Employee class in it:

using System.ComponentModel.DataAnnotations;
 
namespace MVC_CustomModelBinder.Models
{
    public class Employee
    {
        [Key]
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public decimal Salary { get; set; }
    }
}

The Employee class above is an Entity class having EmpNo as a primary key. Now add the following ApplicationEntities class to generate a table from the Employee class.

public DbSet<Employee> Employees { get; set; }

Step 4 – Add an MVC controller in the Controllers folder and call it ‘Employee controller’. Add the following action methods in the controller.

using System.Linq;
using System.Web.Mvc;
using MVC_CustomModelBinder.Models;
using System.Xml.Serialization;
 
namespace MVC_CustomModelBinder.Controllers
{
    public class EmployeeController : Controller
    {
        ApplicationEntities ctx;
        public EmployeeController()
        {
            ctx = new ApplicationEntities();
        }
 
        // GET: Employee
        public ActionResult Index()
        {
            var Emps = ctx.Employees.ToList();
            return View(Emps);
        }
        public ActionResult Create()
        {
            var empPostedData = new XmlSerializer(typeof(Employee));
            var Emp = (Employee)empPostedData.Deserialize(HttpContext.Request.InputStream);
            ctx.Employees.Add(Emp);
              
            return View("Index") ;
        } 
    }
}

Ensure you add a breakpoint on this method to test it. You can use fiddler tools to test the data.

Step 5 – Access the Fiddler tool to this URL (http://localhost:3033/Employee/Create) in the composer with the XML data. Now run the MVC app. Click on the Execute button to execute the call. It will display the following result in Emp object declaration in code:

This code displays the posted Employee data. However, we require a mechanism with which the posted data is auto-mapped with CLR object. That’s where ModelBinder comes into the picture. To implement an infrastructure that helps the posted XML data to be mapped with Employee object, a Custom Model Binder can be used. 

Step 6 – Now add a new folder in the project and name it CustomModelBinders. And in that folder, add a class file using the following code:

using System;
using System.Web;
 
using System.Web.Mvc;
using System.Xml.Serialization;
 
namespace MVC_CustomModelBinder.CustomModelBinders
{
    public class XMLToObjectModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                //1.
                var model = bindingContext.ModelType;
                //2.
                var data = new XmlSerializer(model);
                //3.
                var receivedStream = controllerContext.HttpContext.Request.InputStream;
                //4.
                return data.Deserialize(receivedStream);
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError("Error", "Received Model cannot be serialized");
                return null;
            }
 
        }
    }
    public class XMLToObjectModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(Type modelType)
        {
            //5.
            var receivedContentType = HttpContext.Current.Request.ContentType.ToLower();
            if (receivedContentType != "text/xml")
            {
                return null;
            }
 
            return new XMLToObjectModelBinder();
        }
    }
 
}

Step 7 – You need to add the above custom model provider class within the application. This will help the app load in the model binder process. So, open Global.asax and include the following line Application_Start() method.

protected void Application_Start()
{
    ModelBinderProviders.BinderProviders.Insert(0, new XMLToObjectModelBinderProvider());
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

The ModelBinderProviders adds the binder provider within your app that was created previously. 

Step 8 – Modify the code of Create Action method in EmployeeController class as shown below:

public ActionResult Create(Employee Emp)
{
    ctx.Employees.Add(Emp);
    ctx.SaveChanges(); 
    return View("Index") ;
}

Now apply a breakpoint on Create Action method and use Fiddler to run the application. Select the same data as shown is Step 5. The posted Employee Data will be displayed as follows:

This code displays de-serialized Data into Employee CLR object. 

In conclusion, Custom Model Binder gives you a mechanism that can help in mapping the data from the request to your ASP.NET MVC Model. Share your view on this tutorial in the comments below. 

Similar Articles

QA and Testing Services

Software testing services are quite necessary to design software that full-fledged meets the requirement and the purpose of software. If you are going to build an app then it must be necessary for you to go for testing phase as here you will get to know the compatibility issues

Adeptia Data Integration

Data integration platform is becoming a valuable technology for not only managing structured or unstructured data but also to aligning people, processes, and technologies. Selecting a robust data connectivity tool is tough as the market is dense with innumerable players. 

Active Ruby

Ruby is an object-oriented programming language that is pretty dynamic. Just because of its dynamic nature it has been being used in a wide range of fields, but it is best known for developing Web Applications, because of the Ruby on Rails framework.

A List of Responsibilities of a Software Tester

Given how entitled our lives have become with the progress in technology, it is not that surprising that most of us are oblivious to the significant contribution of software testers in our day to day life in this digitized existence.

Android App Development Company

Worldwide end users market share for the Android O.S is 80.7% and that of iOS is 17.7%. Here are the 7 reasons why you need an Android app Development Company.

Now we are at the mid of 2017 and it is already going by fast. It's now time to avoid summarizing the accomplishments that we have achieved in 2016 and commence observing the latest developments in the mobile iphone app testing sphere.

Robotic Process Automation

In the competitive world, organizations are integrated with many software solutions. There are lots of radical solutions are helpful for the organization in order to optimize an excellent workflow. Today, most of the companies are highly benefitted for the Robotic software tool.

Software System Testing

Software testing is always considered as the main component in software development lifecycle as it helps in detecting the bugs in the existing software and also helps in maintaining the software quality.

How to Update Outdated Drivers on Windows

Drivers on the computer are the essential software tools which help Windows operating system to interact with system’s hardware devices. Thus, it becomes important to keep these drivers updated all the time for improved system performance.