How to set value into HTML5 date field from Asp.Net MVC Razor?
Solution 1
Why instead you just use html helper as shown :-
@Html.TextBox("txtJoiningDate", Model.JoiningDate.Value ,"{0:yyyy-MM-dd}",new{ @style="width:100%", type="date" })
Solution 2
For Html5 input type="date" fields, the values must be specified in the format "yyyy-MM-dd". Once you set it in that format, you will see the value assigned on screen.
Solution 3
using Html helper
@Html.TextBox("txtJoiningDate", Model.JoiningDate.Value ,"{0:MM/dd/yyyy}")
In Model
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public Nullable<System.DateTime> JoiningDate{ get; set; }
This is works for me
Solution 4
You sure you tried yyyy-MM-dd format? Check out this fiddle, works properly on Chrome
<input id="txtJoiningDate" type="date" style="width: 100%;" value="2010-12-25" /> -> works
<input id="txtJoiningDate" type="date" style="width: 100%;" value="2010/12/25" /> -> will not work
Solution 5
@Html.EditorFor(x => x.JoiningDate)
also in your model:
[DisplayName("Joining date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? JoiningDate { get; set; }
Comments
-
vpv almost 2 years
I found a similar question here but that do not work for my case. Please look at the screen shot below. When I render data in an Edit form, all data was set to the controls properly except the highlighted date field. When I inspect the element, I found that the value is there but for some reason it is not showing in the field.
Here is the code I used to set value into this date field. I tried both "yyyy-MM-dd" & "MM/dd/yyyy" format but none worked.
<td>Joining Date</td> <td> @{ if(Model.JoiningDate != null) { <input id="txtJoiningDate" type="date" style="width: 100%;" value="@String.Format("{0:MM/dd/yyyy}",Model.JoiningDate.Value)" /> } else { <input id="txtJoiningDate" type="date" style="width: 100%;" /> } } </td>
Edit