Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a ShortDate string format with Html.TextBoxFor

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
like image 975
JTrott Avatar asked Dec 06 '22 01:12

JTrott


1 Answers

<%: 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) %>
like image 109
Darin Dimitrov Avatar answered Dec 09 '22 14:12

Darin Dimitrov