DisplayFormatAttribute not working

2019-07-25 11:57发布

I am using MVC3 with Razor and EntityFramework. To handle event scheduling I have a StartDate, StartTime, EndDate, EndTime using jquery datepicker and timepicker. I am trying to use the DisplayFormatAttribute in my ViewModel but the Textbox keeps showing the entire DateTime string.

In my viewmodel I have the following properties:

    [DisplayFormatAttribute(DataFormatString = "{0:mm/dd/yyyy}")]
    public DateTime StartDate   { get; set; }

    [DisplayFormatAttribute(DataFormatString = "{0:h:mm tt}")]
    public DateTime StartTime   { get; set; }

And my view looks like this:

    <div id="event-datetime-range" style="display:inline">
        <span id="event-startdatetime">
            @Html.TextBoxFor(model => model.StartDate, new { placeholder = "Start Date", id = "event-start-date", @class = "event-datepicker" });

            <span class="event-timerange">at</span>
            @Html.TextBoxFor(model => model.StartTime, new { placeholder = "Time", id = "event-start-time", @class = "event-timepicker event-timerange" })
        </span>

Can anyone please tell me what I am doing wrong? Thanks in advance!

3条回答
forever°为你锁心
2楼-- · 2019-07-25 12:24

Try using [DisplayFormat(DisplayFormatString={"0:d})] .

查看更多
时光不老,我们不散
3楼-- · 2019-07-25 12:31

the DisplayFormat attribute is for use with the Html.DisplayFor() method and not for use with Html.TextBoxFor. I would recommend using a custom EditorTemplate to display your date format. Or use jQuery.

查看更多
贪生不怕死
4楼-- · 2019-07-25 12:31

If you are using the JQuery date picker use the dateFormat option when you create the control.

jquery datepicker

Also in the date/time format "mm" is minutes where "MM" is months.

You might also want to try @Html.EditorFor() instead of @Html.TextBoxFor()

查看更多
登录 后发表回答