C# EditorTemplate就位时DateTime的自定义绑定不起作用
由于MVC3为DateTime提供的默认编辑器不支持HTML5,因此我编写了以下自定义编辑器模板: DateTime.cshtmlC# EditorTemplate就位时DateTime的自定义绑定不起作用,c#,asp.net-mvc-3,model-binding,mvc-editor-templates,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 forma
@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
}
}" />
我已经注册了Global.asax.cs:
System.Web.Mvc.ModelBinders.Binders.Add(typeof(DateTime), new IsoDateModelBinder());
System.Web.Mvc.ModelBinders.Binders.Add(typeof(DateTime?), new IsoDateModelBinder());
但是,当自定义编辑模板就位时,根本不会调用自定义活页夹。我已经从解决方案中删除了它,并且正确地调用了自定义活页夹-尽管在这一点上,格式是错误的,因为自定义编辑器没有提供正确的控件
那么,我遗漏了什么呢?结果是我让它工作了。我怀疑这两种能力之间存在干扰,但事实并非如此 问题在于编辑器模板不完整。对于要返回值的表单,它们当然需要有一个值和一个名称。如果名称不存在,则不会将值发布回服务器,当然,也不会调用绑定器,因为没有要绑定的值 正确的模板应该更像这样:
@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
@model DateTime?
<input type="date" id="@Html.IdFor(model => model)" name="@Html.NameFor(model => model)" value="@{
if (Model.HasValue) {
@Model.Value.ToISOFormat()
}
}" />