How to set value in HTML5 date field from Asp.Net MVC Razor?

I found a similar question here , but it doesn't work for my case. Take a look at the screenshot below. When I process the data in the edit form, all the data has been correctly set to the controls except for the highlighted date field. When I inspect the element, I find that the value is there, but for some reason it doesn't appear in the field.

Here is the code I used to set the value to this date field. I tried the format "yyyy-MM-dd and " MM / dd / yyyy 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>

      

enter image description here

Edit
enter image description here

+3


source to share


5 answers


Why instead you just use the html helper as shown: -



@Html.TextBox("txtJoiningDate", Model.JoiningDate.Value ,"{0:yyyy-MM-dd}",new{ @style="width:100%", type="date" })

      

+8


source


using Html helper

@Html.TextBox("txtJoiningDate", Model.JoiningDate.Value ,"{0:MM/dd/yyyy}")

      

In the model



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

      

This works for me

+2


source


@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; }

      

+1


source


For input fields of type Html5 = "date", the values ​​must be specified in the format "yyyy-MM-dd". After you set it in this format, you will see the value assigned on the screen.

+1


source


Are you sure you tried the yyyy-MM-dd format? Check fiddle , works correctly in 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

      

0


source







All Articles