JohnDoe
JohnDoe

Reputation: 75

Custom Model Binders in ASP.NET MVC 5

Is custom model binders still being used in ASP.NET MVC 5? I cannot even get it to compile. I have the following binding code:

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;

namespace Playground.CustomModelBinders
{
    public class CalendarModelBinder : IModelBinder
    {
        public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            throw new NotImplementedException();
        }
    }
}

The problem comes when I try to register it:

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            ModelBinders.Binders.Add(typeof(CalendarModelBinder),new CalendarModelBinder()); 

        }

I get the following error:

Error   CS1503  Argument 2: cannot convert from 'Playground.CustomModelBinders.CalendarModelBinder' to 'System.Web.Mvc.IModelBinder'    

Upvotes: 2

Views: 2341

Answers (1)

Triet Doan
Triet Doan

Reputation: 12083

It seems you're using a wrong namespace. IModelBinder should be in System.Web.Mvc namespace.

And the method should be:

public object BindModel(
    ControllerContext controllerContext,
    ModelBindingContext bindingContext
)

You can check the MSDN.

On my second check, I found out that you're making a mistake in this line:

ModelBinders.Binders.Add(typeof(CalendarModelBinder),new CalendarModelBinder());

The first parameter of Add method should be the type of the bound model, not the ModelBinder. It should be something like:

ModelBinders.Binders.Add(typeof(MyCalendar),new CalendarModelBinder());

Upvotes: 3

Related Questions