【问题标题】:In ASP.NET MVC 4, is there a way I can add a custom DateTime model binder for a single action?在 ASP.NET MVC 4 中,有没有一种方法可以为单个操作添加自定义 DateTime 模型绑定器?
【发布时间】:2013-04-06 01:36:58
【问题描述】:

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

控制器动作是:

public ActionResult Registration_Post(RegistrationDetails model)

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

我不想覆盖整个应用的 DateTime 绑定 - 只是为了这个单一的操作(或者,如果更简单,控制器)。

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

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

但是,我似乎需要为整个 RegistrationDetails 类创建一个自定义活页夹,这似乎有点矫枉过正。

另外,我不希望将自定义格式放在模型属性上,因为该类在其他地方使用,所以我污染了该类。

我正在使用 MVC4。

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

【问题讨论】:

  • 将属性直接放在参数上应该可以工作。你得到了什么——只是没有自定义活页夹行为?
  • 参数字典包含“WebUi.Controllers.AccountController”中方法“System.Web.Mvc.ActionResult Registration_Post(WebUi.Domain.RegistrationDetails)”的参数“模型”的无效条目。字典包含“System.DateTime”类型的值,但参数需要“WebUi.Domain.RegistrationDetails”类型的值。参数名称:参数
  • 当您需要返回预期类型 RegistrationDetails 时,听起来您正在从自定义绑定器返回 DateTime。我意识到您的“特殊要求”仅适用于模型中的一个字段,但您必须将模型作为一个整体来处理......

标签: asp.net-mvc datetime asp.net-mvc-4 model-binding custom-model-binder


【解决方案1】:

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

在您的 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
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2020-07-26
    相关资源
    最近更新 更多