Display a formatted date in a TextBoxFor()

I'm using MVC4 and Entity Framework to develop an intranet web app. I have a list of persons which I can edit. When I access the edit view, in the textbox "Start date", the date is displayed like this : 7/11/2013 00:00:00 . What I want to do is to display it in the format yyyy/MM/dd. I tried the String.Format("{0:yyyy/MM/dd}", item.StartDate) but it does not work. I also tried with the annotation [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")] but it does not work neither.

In my view I have this :

<div class="editor-field">
        @Html.TextBoxFor(model => model.StartDate, new { @class = "datepicker" })
        @Html.ValidationMessageFor(model => model.StartDate)
    </div>

Any idea about how to do?


@Html.TextBoxFor(m => m.StartDate, 
    new { @Value = Model.StartDate.ToString("yyyy/MM/dd"), @class="datepicker" })

enter image description here

Your question asks for EditorFor() but the code you provided uses TextboxFor().

In your Model (e.g. MyModel.cs), you should have:

public class MyModel
{
    [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }
}

In your View (e.g. Index.cshtml), you simply use it like you wrote it:

@Html.EditorFor(m => m.StartDate, new { htmlAttributes = new { @class = "datepicker" } })

It works as expected.

By doing it that way (instead of altering the way it's displayed in your View), you could reuse your model somewhere else and don't have to specify how to display the date in your View. So, if for some reason, you have to change the display format, you would only need to change it once.

The solution also works for MVC 5.


The top easy for me , was adding the type attribute,

@Html.EditorFor(model => model.FechaRegistro, new { htmlAttributes = new { @class = "form-control oso" ,@type = "date"  } })

Html.EditorFor also work


@Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "datepicker", @Value = model.StartDate.ToString("yyyy/MM/dd") } })