你需要更新你的模型看起來像這樣:
public class Person
{
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-mm-dd}")]
public DateTime DateOfBirth { get; set; }
}
你的控制器可能需要首先分析字符串:
public ActionResult Index()
{
Person p = new Person();
p.DateOfBirth = DateTime.ParseExact("20120801","yyyyddmm",System.Globalization.CultureInfo.InvariantCulture);
return View(p);
}
然後將其顯示在你看來,你將需要使用類似下面的代碼:
<fieldset>
<legend>Person</legend>
<div class="editor-label">
@Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateOfBirth)
@Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
出於某種原因,迪splayFormat屬性只能用於EditorFor和DisplayFor助手。
嘗試答案張貼在這裏: http://stackoverflow.com/questions/5252979/assign-format-of-datetime-with-data-annotations – chris