2

I want to model bind a collection of objects in a HTTP GET like so:

public class Model
{
    public string Argument { get; set; }
    public string Value { get; set; }
}

[HttpGet("foo")]
public IActionResult GetFoo([FromQuery] IEnumerable<Model> models) { }

Firstly, what is the default behaviour in ASP.NET Core in this scenario? The model binding documentation is sparse but does say I can use property_name[index] syntax.

Secondly, if the default is no good, how would I get a decent looking URL by building some kind of custom model binder that I could reuse as this is a fairly common scenario. For example if I want to bind to the following format:

?Foo1=Bar1&Foo2=Bar2

So that the following objects are created:

new Model { Argument = "Foo1", Value = "Bar1" }
new Model { Argument = "Foo2", Value = "Bar2" }
Muhammad Rehan Saeed
  • 35,627
  • 39
  • 202
  • 311

1 Answers1

1

Not much changed since MVC 5. Given this model and action method:

public class CollectionViewModel
{
    public string Foo { get; set; }
    public int Bar { get; set; }
}


public IActionResult Collection([FromQuery] IEnumerable<CollectionViewModel> model)
{

    return View(model);
}

You can use the following query strings:

?[0].Foo=Baz&[0].Bar=42 // omitting the parameter name
?model[0].Foo=Baz&model[0].Bar=42 // including the parameter name

Note that you cannot mix these syntaxes, so ?[0].Foo=Baz&model[1].Foo=Qux is going to end up with only the first model.

Repetition without indices is not supported by default, so ?model.Foo=Baz&model.Foo=Qux isn't going to fill your model. If that's what you mean by "decent looking", then you'll need to create a custom model binder.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • What about creating a custom model binder? – Muhammad Rehan Saeed Oct 25 '16 at 09:15
  • @Muhammad well I guess that's a separate question, in which you should explain what format of the query string you'd like to support and what you have tried. – CodeCaster Oct 25 '16 at 09:46
  • Update the question. – Muhammad Rehan Saeed Oct 25 '16 at 10:33
  • Don't ask two questions in one, that makes it too broad. The first was "how does collection parameter binding work", which this answer answers. If you want to create a custom model binder to support a different format, that's a different question. And again, read [ask] and share your research. – CodeCaster Oct 25 '16 at 10:35