1
在默認編輯器,MVC3提供的DateTime不是HTML5友善,我已經編寫了下面的自定義編輯模板不工作:的日期時間自定義綁定時EditorTemplate到位
(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());
然而,當自定義編輯模板就位,定製粘合劑贏得一點都不會打電話。我已經從解決方案中刪除了它,並且正確調用了自定義聯編程序 - 儘管此時該格式是錯誤的,因爲自定義編輯器沒有提供正確的控件。
那麼,我錯過了什麼?