0

Can't populate date inputs from my model in ASP.NET Core MVC. It's accepted, but no display dates in input after filter submit Here's the code :

In model class:

public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }

In the view:

<span>Date after: </span><input type="date" name="startDate" id="startDate" asp-route-filterString="@Model.FilterString" class="form-control" value="@Model.StartDate"/>
<span>Date before: </span><input type="date" name="endDate" id="endDate" asp-route-filterString="@Model.FilterString" class="form-control" value="@Model.EndDate"/>

In controller:

public async Task<IActionResult> Index(...,
           string filterString,
           DateTime? startDate = null,
           DateTime? endDate = null,)
{
    // ...
    var model = new ViewModel(...)
                    {
                        StartDate = startDate.GetValueOrDefault(),
                        EndDate = endDate.GetValueOrDefault(),
                        // ... more code
                        FilterString = filterString,
                    };

    return View(model);
}
6
  • I believe this answers your question: stackoverflow.com/questions/51041234/… Commented Aug 14, 2022 at 22:45
  • no, yo link is about editing the model. I need to filter the items on the page by date range filter with saving inputs values frm model. "asp-for" isn't workin Commented Aug 15, 2022 at 14:20
  • You said that the problem is that the date inputs (<input type="date" />) are not populated with the value sent from model, so the inputs stay empty, right? Commented Aug 15, 2022 at 16:57
  • yes, but the model value was set from the selected value Commented Aug 15, 2022 at 17:05
  • Try value="@Model.EndDate?.ToString("yyyy-MM-dd")" instead of value="@Model.EndDate" Commented Aug 15, 2022 at 17:43

1 Answer 1

0

HTML5 input with type="date" expects the value to be a specific format which is yyyy-MM-dd. You need set this format to the values and it will work:

<input type="date" asp-for="EndDate" value="@Model.EndDate?.ToString("yyyy-MM-dd")" />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.