Display a formatted date in a TextBoxFor()

前端 未结 6 1725
长情又很酷
长情又很酷 2020-12-04 18:52

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\", t

6条回答
  •  星月不相逢
    2020-12-04 19:44

    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.

提交回复
热议问题