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

Why Dynamics CRM Overpowers Other CRMs As The ‘Enterprise CRM Suite of Choice’?

Irrespective of the field of work of any business, customers remain the most vital asset of the company. It is extremely important for every company to manage and maintain long-lasting bonds with the customers. Relationships with the customers is certainly the key foundation of enhancing the business

marketing enablement software

In today's complex business world, organizations will always struggle to create and execute effective targeted marketing campaigns which can potentially drive sales. The content marketing arena has become extremely competitive in the last few years and this implies that organizations must invest wisely to enhance the popularity of their brand. 

omr technology

Education plays a crucial role in the life of not only students but also the teachers. “Teaching with technology” is the new slogan in educational field that is sustaining the value of learning and examination process in the 21st era of automation. OMR- Optical mark reader is one of the many technologies that are effectively being implemented in the education system.

best content management tools

Whether you are an established or beginner content marketer, you probably understand the importance of adopting effective content marketing programs in today’s competitive B2B marketing landscape. Content marketing is arguably the most efficient methods of developing your brand presence, boosting audience engagement as well as driving sales.

Workflow Management

Are you worried about the turn-around time and quality in your business processes? If so, we have put together some workflow management systems that you can improve productivity.

6 Tools to Easily Build a Powerful Workflow

One of the most challenging tasks in every business is to make sure that all essential tasks and activities would be coordinated in an effective flow. In other words, they need to implement a good daily routine process so that files, information, and jobs are passed quickly and timely from individuals to individuals.

Some Of The Key Advantages Of Software Testing

Software testing is an essential part of assuring the quality of software. It is a plan which is carried out to discover the errors and mistakes when the whole process is completed.

Microsoft Dynamics Damn Creatively

Microsoft Dynamics 365 has become the talk of the town. The ERP solution has become the go-to ERP software solution for small, medium, and large organizations. Some of the well-known manufacturing companies worldwide are using the solution to manage their business operations more efficiently and cost-effectively.

blogging

Bill Gates, co-founder of Microsoft, was once quoted as saying that “the Internet is becoming the town square for the global village of tomorrow.” But if you were attending an event in your local town square would you leave your valuables unattended or your vehicle unlocked?