Why is my date input not reading the model value?

后端 未结 2 863
不思量自难忘°
不思量自难忘° 2020-12-21 06:14

I\'m a server side guy trying to teach myself a bit of CSS, Javascript, jQuery etc. I have written a little test project that loads up a model and displays the values in si

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 06:46

    The type="date" attribute renders the browsers HTML5 datepicker. In order for this to work correctly, the format needs to be yyyy-MM-dd (ISO format), so it needs to be

    @Html.TextBoxFor(m => m.Date, "{0:yyyy-MM-dd}", new { @type="date" })
    

    Alternatively you can set data attributes on the property

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

    and use

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

    which adds the type="date" attribute and uses the correct format.

    Side notes:

    1. The HTML5 datepicker is only supported in recent versions of Chrome
    2. Using EditorFor() (in MVC-4) will not allow you to set the id attribute, but its not clear why you would need to change the default id="Date" to id="ondate"

提交回复
热议问题