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

How Salesforce Financial Services Cloud (FSC) can transform Insurance Operations?

Among the solutions developed over the past few decades, Salesforce Financial Services Cloud (FSC) has emerged as the definitive choice for gaining flexibility, visibility, and long-lasting, inclusive growth in the financial sector.

open source

Open source software (OSS) is distributed with its source code, which means it can be distributed, modified, and used freely with the original rights. Most users never see the source code, a critical part of the software. 

Dynamics CRM

It's one of the keystones, basic but key in the successful highly competitive modern business environment, where the connection with the customer is a must.

Python for small scale businesses

The speed of progress in the modern business landscape is quite relentless. For small-scale companies, this implies that keeping up with this progress is not simply gainful but fundamentally significant for their survival. And what does success in such an environment demand?

Benefits of Power Automate for the Finance Industry

The finance sector needs to battle many difficulties in the modern and quick-moving digital landscape. Be it exploring the unpredictable snare of official guidelines or overseeing tremendous volumes of data - - financial establishments are feeling the pressure to succeed. This demanding environment, in turn, often leads to exhausted teams, costly manual errors, and inefficiencies that can be chalked up to repetitive tasks

digital transformation

The manufacturing industry, vital to the world economy, is at a pivotal intersection. I mean that, yet again, changes are afoot in the sector, this time driven by digital transformation as it represents a profound change in the very essence of how manufacturers operate, think, and drive innovation.

How Can Payment Gateways Benefit the Travel Industry

Technology helps make things easier and faster. Digitization is one of the aspects of technology that has changed how we live and work. It has brought many benefits for businesses, especially the travel industry. Customers can search online for the schemes offered and easily book trips, but payments need to be completed with ease.

DataOps

In an article published by The Economist in 2017, while describing the astounding growth of titan companies like Google, Apple, Facebook, and Microsoft, it was mentioned how data had become “the oil of the digital era.”

The Impact of AR & VR on the Media and Entertainment Industry

Harnessing the latest technology to create and distribute content is an ongoing process in the media and entertainment industry. Changes in consumer behavior and demands, along with continuous and rapid technological advancements, are reshaping the industry