如何在Html.TextBoxFor中使用ShortDate字符串格式

使用Entity Framework和MVC2,我有一系列日期文本框,我想以短日期格式显示模型中的数据,但我必须使用Html.TextBoxFor才能使更新代码正常工作(尝试使用HTML) .Textbox数据永远不会保存到模型中)。

 model.Item.Date, String.Format("{0:d}", Model.Item.Date))%> 

我已经尝试过操作字符串格式表达式,并将元数据添加到映射到Entity Framework模型类的部分类中,但是我仍然在表单渲染中填充以下文本框:

 01/01/2011 00:00:00 

而不是

 01/01/2011 

 <%: Html.EditorFor(model => model.Item.Date) %> 

在您的视图模型上:

 [DataType(DataType.Time)] [DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")] public DateTime Date { get; set; } 

更新:

完整示例:

模型:

 public class MyModel { public Item Item { get; set; } } public class Item { [DataType(DataType.Time)] [DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")] public DateTime Date { get; set; } } 

控制器:

 public class HomeController : Controller { public ActionResult Index() { return View(new MyModel { Item = new Item { Date = DateTime.Now } }); } } 

视图:

 <%: Html.EditorFor(model => model.Item.Date) %>