How to utilize the Html ShortDate string format. TextBoxFor

asp.net asp.net-mvc asp.net-mvc-2 c# entity-framework

Question

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
1
4
4/10/2013 8:27:01 PM

Accepted Answer

<%: 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) %>
16
9/21/2010 8:58:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow