How to use a ShortDate string format with Html.TextBoxFor

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

And on 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) %>
Share:
15,023
JTrott
Author by

JTrott

Updated on June 04, 2022

Comments

  • JTrott
    JTrott almost 2 years

    Using Entity Framework with MVC2, I have a series of date textboxes, that I want to display data from the model in a 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 gets saved to the model).

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

    I've tried manipulating the string format expression, and have added metadata to a partial class mapped to the Entity Framework model class, however still I get the following populating my textboxes at form render:

    01/01/2011 00:00:00 
    

    rather than

    01/01/2011