0

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?

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
Steve Cross
  • 89
  • 1
  • 13
  • 1
    There are some usage examples here: https://stackoverflow.com/questions/33470849/html-editorfor-datetime-not-displaying-when-set-a-default-value-to-it – mahbad Oct 18 '21 at 17:59
  • 1
    Does this answer your question? [How to set value of default date in DateTime EditorFor](https://stackoverflow.com/questions/58055524/how-to-set-value-of-default-date-in-datetime-editorfor) – mahbad Oct 18 '21 at 18:03
  • 1
    https://stackoverflow.com/questions/21393870/mvc4-date-picker-with-default-date – mahbad Oct 18 '21 at 18:06

2 Answers2

1

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

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
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.

Steve Cross
  • 89
  • 1
  • 13