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

Childcare Management Software

It is school owners and school manager’s responsibility to run an effective school and also offer high- class childcare. But, there are some challenges that everyone has to face when it comes to run a kindergarten school especially

Windows registry

Let us understand registry which is the most critical part of a computer. It will interest you that registry clean up can be used to optimize the system.

Computer system’s speed and performance start diminishing over time due to prolonged use. A lot of data accumulates on your system which affects system performance negatively. 

www.hiri.com

Remember Microsoft Outlook? Ok, sure you do, but let’s face some facts. Microsoft Outlook has been around for a long time, some two decades this year.

Flashing Signs your Payroll System needs a Reboot

When should a business consider changing its payroll system or process? This question has been a concern for a number of business leaders all over.

duplicate file finder foe Mac

Duplicate files accumulate on your system due to various reasons like file sharing, file downloading, data backup etc. Initially, these files don’t affect your system but once they accumulate in large numbers

hard disk

When you bring your brand new system it works efficiently and smooth. Due to prolonged use, it starts creating issues like a slow startup, slow speed & performance, and other issues

Duplicate file finder

Duplicate files on any device can create serious problems with speed and performance of the system. Duplicate file finder tools can help you find a solution to this problem. 

Software Outsourcing Company

Software and outsourcing are becoming the need of the hour. With software requirements in all the sectors such as industries, medical and constructional sectors etc.