Search code examples
ajaxasp.net-coredata-bindingrazor-pages

Why can't I bind dates in query string with GET parameters?


I am using ASP.NET Core 3.1. I am trying to bind dates in a query string to a PageModel using GET. Here is my query string:

?id=15+startDate=1900-01-01+endDate=1900-01-01

Here is the signature of my OnGet:

public void OnGet(int id, DateTime startDate, DateTime endDate)

The values are always 0, 1/1/0001 00:00:00, 1/1/0001 00:00:00 respectively.

If I remove the dates and just pass the id, it works fine. Why do the dates in the query string break everything including the id? I have also tried changing the data types from DateTime to string and it still breaks with the string parameters always being null.


Solution

  • The separator for parameters in a query string is &, not + as your example has. Corrected:

    ?id=15&startDate=1900-01-01&endDate=1900-01-01
    

    An arguably better approach with datetime parameters is to accept them as strings, then use DateTime.TryParse to parse with control over expected format. That way you'll always have the opportunity to inspect the string value provided and decide if you want to convert it to a DateTime, and how.