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

app developers gold coast brisbane

When you are creating an app, there are many elements about it that you need to know. Elements that you might not even know about. This is why you need to make sure that you are getting to know everything before you decide to create an app for your business.

app developers gold coast brisbane

Many think that it is easy to develop a mobile app. But there are so many things that you need to make sure about, and consider. It isn’t as easy as you might think.

app developers gold coast brisbane

Do you know that when you develop a successful app that resonates with people, that you are also inadvertently strengthening your brand as well? That you are ultimately ensuring that your business gets to enjoy more success and prosperity?

app developers gold coast brisbane

Everyone is trying to create an app that is superior to the previous person’s effort. App developers are always trying to improve and evolve the features of an app to give it the best chance of becoming an in-demand product that many will want to download.

Internet Explorer for Mac and Windows

I have my own websites, and I am a programmer. I needed an online platform where I can gather the data about what I was developing. So, I came across Comparium to use on Internet Explorer for Mac, where I could test different screens of the websites and the apps I was developing.

Top 4 Stats to Make You Invest In EHS Software

Are safety and compliance crucial for your business operation? If yes, then have you considered deploying EHS software in your organization? If not, then these eye-opening facts will make you invest in EHS (Environmental, Health, and Safety) software.

 Efficient Mobile App Onboarding

App onboarding is crucial as it decides the success or failure of the application. It is the first point of contact in a mobile app user’s journey. The onboarding process covers a series of screens.

Increase Productivity with SharePoint

It is a highly competitive world, and companies are continually striving to do better each day to improve productivity and increase overall efficiency. In any business, managing documents, exchanging data through emails, and scheduling meetings requires continuous collaboration within the team.

10 Best Practices for Choosing a Penetration Testing Company

Penetration testing has grown into one of the most common engagements for the current security-aware companies. There are numerous reasons for running a pentest, such as better security guards, diminished risk levels or meeting strict compliance requirements