DataType attribute wrecking jQuery datepicker on Datetime field

那年仲夏 提交于 2020-03-01 07:24:19

问题


I am using MVC 4 and Razor views and am having trouble understanding why the Edit view on my Date field is not binding properly to the built in jQuery datepicker.

The field is of datatype Date in the Database, and DateTime in the domain model. I do not wish to show time, only the date. The field is required and needs formatting.

My view looks like this :

<div class="editor-label">
    @Html.LabelFor(model => model.Appointment.EndDate)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Appointment.EndDate)
    @Html.ValidationMessageFor(model => model.Appointment.EndDate)
</div>

If my metadata on this field is

[Required(ErrorMessage = "End Date must be a valid date, like 05/13/2016.")]
[DataType(DataType.Date)]
[Display(Name = "End Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public object EndDate { get; set; }

then my editor output on edit.cshtml is this:

<input class="text-box single-line" data-val="true" data-val-date="The field End Date must be a date." data-val-required="End Date must be a valid date, like 05/13/2016." id="Appointment_EndDate" name="Appointment.EndDate" type="date" value="05/09/2013">

this draws a jQuery datepicker BUT WITHOUT SETTING THE VALUE.

If I remove the DataType attribute from my metadata and leave everything else the same:

[Required(ErrorMessage = "End Date must be a valid date, like 05/13/2016.")]
[Display(Name = "End Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public object EndDate { get; set; }

then my editor output is this:

<input class="text-box single-line valid" data-val="true" data-val-date="The field End Date must be a date." data-val-required="End Date must be a valid date, like 05/13/2016." id="Appointment_EndDate" name="Appointment.EndDate" **type="datetime"** value="05/09/2013">

this draws a plain text box (no datepicker) with the value properly set.

I would like to use the datepicker but set the correct value, how can I do this?


回答1:


try the following code:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? EndDate { get; set; }

(i used a nullable datetime; but it isnt really needed)

and in the GUI use:

@Html.EditorFor(m => m.EndDate )

this should work.



来源:https://stackoverflow.com/questions/16324735/datatype-attribute-wrecking-jquery-datepicker-on-datetime-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!