2011-12-14 28 views
1

格式化,我有以下CSHTML在我看來 我也有我的模型下面的代碼MVC3 @HTMLEditFor用的DatePicker如何與ShortDate

  <td class="editor-field"> 
      @Html.EditorFor(model => model.Required_From) 
      @Html.ValidationMessageFor(model => model.Required_From) 
     </td> 
    <script type="text/javascript"> 
     $(function() { 
       //debugger 
      $("#Required_From").datepicker({ dateFormat: "mm/dd/yy", changeYear: true,  changeMonth: true }); 
      }); 
      $(function() { 
       //debugger 
       $("#Required_To").datepicker({ dateFormat: "mm/dd/yy", changeYear: true, changeMonth: true }); 
      }); 
    </script> 

在我的模型,我有以下代碼:

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Required_To", DbType="DateTime NOT NULL")] 
    public System.DateTime Required_To 
    { 
     get 
     { 
      return this._Required_To; 
     } 
     set 
     { 
      if ((this._Required_To != value)) 
      { 
       this._Required_To = value; 
      } 
     } 
    } 

我需要能夠展現出短日期格式,但是當我這樣做,我得到了以下錯誤: 「模板只能與現場訪問,訪問屬性,一維數組的索引,或單PARAM使用閱讀自定義索引表達式。「 有沒有辦法使用短日期格式的模型和日期選擇器? TIA Bruce

回答

2

我會建議您在視圖中始終使用視圖模型,並且絕不會將域模型傳遞給它們。因此,在您的視圖模型,你可以用[DisplayFormat]屬性裝飾的財產,就像這樣:

public class MyViewModel 
{ 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")] 
    public DateTime RequiredFrom { get; set; } 
} 

,然後當你寫,因爲你的觀點會被強類型的視圖模型:

@Html.EditorFor(model => model.RequiredFrom) 

你將獲得所需的格式。

此,如果你想違背好的做法和不使用視圖模型雖這麼說,你總是可以試試這個:

@Html.TextBox("Required_From", Model.Required_From.ToShortDateString()) 
+0

感謝您的幫助強類型的觀點是我在用。 DisplayFormat工作時不需要右鍵單擊並應用使用的System.ComponentModel,但是這種小打嗝正是我所需要的。 – user1011441 2011-12-14 19:31:18