I'm clearly missing something obvious here. As the title says, if I have this signature:
public async Task<IActionResult> Details(int? id, DateTime? dateFrom, DateTime? dateTo)
I always get null
's for the dateFrom
and dateTo
. If I use this signature:
public async Task<IActionResult> Details(int? id, string dateFrom, string dateTo)
I get the dates as a string as such: "27/11/2018 00:00:00" and "27/12/2018 23:59:59"
I've also tried non-nullable DateTime
but it doesn't work either.
On the front end I have this (which is populated correctly from the model by the way):
<div>
<p>Filter</p>
@Html.EditorFor(model => model.DateFrom, new { @class = "form-control" })
@Html.EditorFor(model => model.DateTo, new { @class = "form-control" })
<a asp-action="Details" asp-route-id="@Model.Id" asp-route-dateFrom="@Model.DateFrom" asp-route-dateTo="@Model.DateTo">Filter</a>
</div>
Why is the default model binder not binding to DateTime
or DateTime?
?
Additionally, if I inspect the Query
in the immediate window I have:
Request.Query["dateFrom"]
{27/11/2018 00:00:00}
Count: 1
Results View: Expanding the Results View will enumerate the IEnumerable
Request.Query["dateTo"]
{27/12/2018 23:59:59}
Count: 1
Results View: Expanding the Results View will enumerate the IEnumerable
Edit after being marked as a duplicate:
I'm not sure the "duplicate" really explains what the problem is - Can the default model binder not bind dates? - If I DateTime.TryParse
on my strings then I get what I need. Creating my own custom model binder seems overkill - I'm not entirely sure what the problem is here. So whilst the questions are similar, the answers to the linked to "duplicate" don't answer all my questions.