Muhammad Rehan Saeed
Muhammad Rehan Saeed

Reputation: 38437

Model Binding Collection Using HTTP GET

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" }

Upvotes: 2

Views: 1906

Answers (1)

CodeCaster
CodeCaster

Reputation: 151586

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.

Upvotes: 1

Related Questions