1

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?

3

2 Answers 2

2

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:

enter image description here

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.