简体   繁体   English

ASP.NET MVC 5中的自定义模型绑定器

[英]Custom Model Binders in ASP.NET MVC 5

Is custom model binders still being used in ASP.NET MVC 5? 自定义模型绑定器是否仍在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'    

It seems you're using a wrong namespace. 看来你正在使用错误的命名空间。 IModelBinder should be in System.Web.Mvc namespace. IModelBinder应该在System.Web.Mvc命名空间中。

And the method should be: 方法应该是:

public object BindModel(
    ControllerContext controllerContext,
    ModelBindingContext bindingContext
)

You can check the MSDN . 您可以查看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. Add方法的第一个参数应该是绑定模型的类型,而不是ModelBinder。 It should be something like: 它应该是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM