Monday, 7 August 2017

Custom Model binding in MVC

Add a Class.

using CustomModelBinding.Models;

namespace CustomModelBinding.Common
{
    public class CustomModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            return new EMP { EID=Convert.ToInt32(controllerContext.HttpContext.Request.Form["EID"]),FIRSTNAME= controllerContext.HttpContext.Request.Form["FNAME"] ,LASTNAME= controllerContext.HttpContext.Request.Form["LNAME"],FULLNAME= controllerContext.HttpContext.Request.Form["FNAME"]+" "+ controllerContext.HttpContext.Request.Form["LNAME"] };
        }
    }
}

Register in global.asax.cs

using CustomModelBinding.Models;

namespace CustomModelBinding
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders[typeof(EMP)] = new Common.CustomModelBinder();
        }
    }
}

No comments:

Post a Comment