在ASP.. NET MVC 4,是否有一种方法可以为单个动作添加自定义DateTime模型绑定器



我试图将表单绑定到控制器中的模型参数。该模型包含一个DateTime字段,我希望在提交表单时绑定该字段。表单字段期望以非标准格式输入日期(由于各种原因,我无法更改)。

控制器动作为:

public ActionResult Registration_Post(RegistrationDetails model)

我只需要在RegistrationDetails类中自定义绑定(DateTime) DateOfBirth属性。所有其他属性都使用默认绑定。

我不想重写整个应用的DateTime绑定——只针对这个单一的动作(或者,如果更简单的话,控制器)。

你知道我该怎么做吗?我尝试在操作上使用ModelBinder属性,如:

public ActionResult Registration_Post([ModelBinder(typeof(CustomDateTimeBinder)]RegistrationDetails model)

然而,我似乎需要为整个RegistrationDetails类创建一个自定义绑定,这似乎有点小题大做。

另外,我不喜欢将自定义格式放在model属性上,因为类在其他地方使用,所以我污染了类。

我用的是MVC4。

谁能告诉我处理这件事的最好方法?

试试这个:创建一个自定义模型绑定器提供程序。

在BindModel方法中,您必须添加逻辑来处理只有来自Registration_Post操作的出生日期具有特殊格式的要求。顺便说一句,您需要绑定整个模型。

using System;
using System.Web.Mvc;
using MvcApp.Models;
public class CustomModelBinderProvider : IModelBinderProvider 
{
    public IModelBinder GetBinder(Type modelType) 
    {
        return modelType == typeof(Person) ? new PersonModelBinder() : null;
    }
}
protected void Application_Start()
{    
    ModelBinderProviders.BinderProviders.Add(new CustomModelBinderProvider());    
}

public class PersonModelBinder : IModelBinder 
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext   
                            bindingContext) 
   {
         //add logic here to bind the person object
   }

最新更新