2011-09-18 46 views
1

日期時間格式以下是在我的viewtimeModel日期時間屬性,我只想在視圖上顯示日期, 任何人都可以幫助我格式化這個。現在林看到01/01/2010 12:00:00 AM格式日期時間在MVC3

public DateTime ModifiedDate 
    { 
     get 
     { 
      return Region.ModifiedDate; 
     } 
     set 
     { 
      Region.ModifiedDate = value; 
     } 
    } 

@Html.TextBoxFor(model => model.ModifiedDate) 
+0

可能重複【如何使一個DateTime在在ASP.NET MVC 3中的特定格式?](http://stackoverflow.com/questions/6001654/how-to-render-a-datetime-in-a-specific-format-in-asp-net-mvc- 3) – Jon

回答

0

我創建了一個看起來像這樣的編輯模板(位於我的解決方案共享\ EditorTemplates文件夾):

@model System.DateTime? 
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty, new { @class = "date"}) 

然後當我想要使用它,

@Html.EditorFor(model => model.RecipeDate, new { @class = "date" }) 
@Html.ValidationMessageFor(model => model.RecipeDate) 

似乎工作對我來說很好。

+0

難道你不得不使用@ Html.Editor而不是@ Html.TextBoxFor? –

+0

@Sergio - 是的,這是正確的。當我輸入時,我的大腦中有「文本框」,因爲這是OP在問題中的含義。我編輯了我的答案,謝謝你的注意。 – itsmatt

+0

它正在工作,但我想使此編輯器字段只讀...有沒有什麼方法... – TJK

4

型號

[DataType(DataType.Date)] 
[DisplayFormat(DataFormatString = "{0:MM/dd/yyy}")] 
public DateTime RecipeDate{ get; set; } 

編輯模板

@model DateTime 
@Html.TextBox("", string.Format(ViewData.TemplateInfo.FormattedModelValue.ToString(), Model), new { @class = "date" }) 

EditorFor不允許自定義屬性,你必須使用一個TextBox或TextBoxFor