I have this in my view:
@Html.EditorFor(model => model.StartDate, new { htmlattributes = new { @class = "datepicker" } })
I have tried this:
@Html.EditorFor(model => model.StartDate, new { htmlattributes = new { @class = "datepicker", @value = "10/18/2021" } })
but it has no effect. How can I control the initial date?
CodePudding user response:
If you want to set the initial value with value
attribute,here is a working demo:
StartDate:
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
view:
<input asp-for="StartDate" class="datepicker" value="2021-10-20" />
result:
CodePudding user response:
Ultimately, it was the Model definition. I had seen this solution in a couple of places and tried it but I tried it incorrectly. I had two dates in the model and I inadvertently changed the wrong one which had no effect.
The model as initially written was:
[DataType(DataType.Date), ErrorMessage = "Date Only"]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Starting Date")]
public DateTime StartDate { get; set; }
What fixed it was:
[DataType(DataType.Date), ErrorMessage = "Date Only"]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Starting Date")]
public DateTime StartDate { get; set; }
Notice the change in DataFormatString in the order. This did in fact fix my issue and if I had changed it in the proper place, I would have seen this myself.