当EditorTemplate到位时,DateTime的自定义绑定不起作用

时间:2012-11-07 18:18:15

标签: c# asp.net-mvc-3 model-binding mvc-editor-templates

由于MVC3为DateTime提供的默认编辑器不是HTML5友好的,我编写了以下自定义编辑器模板:

(DateTime.cshtml)

@model DateTime?

<input type="date" value="@{ 
    if (Model.HasValue) {
        @Model.Value.ToISOFormat() // my own extension method that will output a string in YYYY-MM-dd format
    }
}" />

现在,这很好用,但后来我遇到了日期没有被正确解析的问题,因为ISO日期没有用默认的DateTime绑定解析。所以,我实现了自己的活页夹:

public class IsoDateModelBinder: DefaultModelBinder
{
    const string ISO_DATE_FORMAT = "YYYY-MM-dd";

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (string.IsNullOrEmpty(value.AttemptedValue))
            return null;

        DateTime date;
        if (DateTime.TryParseExact(value.AttemptedValue, ISO_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out date));
            return date;

        return base.BindModel(controllerContext, bindingContext);
    }
}

我已经注册了它(Global.asax.cs):

System.Web.Mvc.ModelBinders.Binders.Add(typeof(DateTime), new IsoDateModelBinder());
System.Web.Mvc.ModelBinders.Binders.Add(typeof(DateTime?), new IsoDateModelBinder());

但是,当自定义编辑模板到位时,根本不会调用自定义活页夹。我已将其从解决方案中删除,并且正确调用了自定义绑定器 - 尽管此时格式错误,因为自定义编辑器未提供正确的控件。

那么,我错过了什么?

1 个答案:

答案 0 :(得分:0)

原来我让它运转了。我怀疑两种能力之间存在干扰,但事实并非如此。

问题出在编辑器模板中,它不完整。对于要发回值的表单,他们需要有一个值(当然)和一个名称。如果该名称不存在,则该值将不会回发到服务器,当然,不会调用活页夹,因为没有要绑定的值。

正确的模板应该看起来像这样:

@model DateTime?

<input type="date" id="@Html.IdFor(model => model)" name="@Html.NameFor(model => model)" value="@{ 
    if (Model.HasValue) {
        @Model.Value.ToISOFormat()
    }
}" />

此外,ISO格式字符串在我这方面是错误的,应该是yyyy-MM-dd而不是YYYY-MM-dd