2012-11-07 58 views
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()); 

然而,當自定義編輯模板就位,定製粘合劑贏得一點都不會打電話。我已經從解決方案中刪除了它,並且正確調用了自定義聯編程序 - 儘管此時該格式是錯誤的,因爲自定義編輯器沒有提供正確的控件。

那麼,我錯過了什麼?

回答

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