Pass complex data object in GET request to MVC controller action

325 views Asked by At

I have model class as below:

  public class HomeFilterModel {
    public string CompanyName { get; set; }
    public string Country { get; set; }
    public DateRange Period { get; set; }
  }

  public class DateRange {
    public DateTime? From { get; set; }
    public DateTime? To { get; set; }
  }

On client side, the data collected as below object:

{
  "CompanyName":"",
  "Country":"Canada",
  "Period":{
            "from":"2018-08-05T04:00:00.000Z",
            "to":"2018-08-09T04:00:00.000Z"
           }
}

It's converted to query string by $.param function and added to URL.

?CompanyName=&Country=Canada&Period%5Bfrom%5D=2018-08-05T04%3A00%3A00.000Z&Period%5Bto%5D=2018-08-10T04%3A00%3A00.000Z

The controller action is as below:

[HttpGet] 
public ActionResult Index(HomeFilterModel filter) {
  return View(filter ?? new HomeFilterModel());
}

The model data filter can get CompanyName and Country values correctly, but Period.From and Period.To are always NULL. I wonder if I have to make customized ModelBinder for this model class specifically? Or I should use different function other than $.param to construct query string in URL?

UPDATED: If query string is changed to

?CompanyName=&Country=Canada&Period.from=2018-08-05T04%3A00%3A00.000Z&Period.to=2018-08-10T04%3A00%3A00.000Z

controller action can get all data correctly. So Period[from] is not acceptable by default model binder, while Period.from is.

Anyone has the simplest and best solution for this?

0

There are 0 answers