Search code examples
c#asp.net-coremodel-view-controllermodel-bindingmodel-validation

`[FromQuery]` IEnumerable<SomeObject> parsing in ASP.NET Core 3.1?


So, when I tested how binding works for an IEnumerable<string> argument, you simply pass the argument's name in the query string, repeatedly, like this: ?a=item1&a=item2&a=item3...

So, what must I write, if I have an argument of type IEnumerable<SimpleObject> a, where SimpleObject is defined as the following:

public class SimpleObject
{
   public string Number { get; set; }
   public string Text { get; set; }
}

in order to successfully bind it to a list of said objects? Or no such default ModelBinder exists for that mapping? (Please provide a sample ModelBinder in that case)


Solution

  • The default model-binding setup supports an indexed format, where each property is specified against an index. This is best demonstrated with an example query-string:

    ?a[0].Number=1&a[0].Text=item1&a[1].Number=2&a[1].Text=item2
    

    As shown, this sets the following key-value pairs

    • a[0].Number = 1
    • a[0].Text = item1
    • a[1].Number = 2
    • a[2].Text = item2

    This isn't quite covered in the official docs, but there's a section on collections and one on dictionaries. The approach shown above is a combination of these approaches.