How to use ShortDate string format using Html.TextBoxFor

Using Entity Framework with MVC2, I have a number of date text fields that I want to display data from the model in short date format, but I have to use Html.TextBoxFor in order for the update code to work (Having tried using HTML.Textbox, the data never will not be saved in the model).

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

I tried to manipulate a string format expression and added metadata to a partial class mapped to the Entity Framework model class, however, I still get the following filling in my text fields when rendering the form:

 01/01/2011 00:00:00 

but not

 01/01/2011 
+4
source share
1 answer
 <%: Html.EditorFor(model => model.Item.Date) %> 

And in your view model:

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

UPDATE:

Full example:

Model:

 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; } } 

Controller:

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

View:

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

All Articles