Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get Dictionary from query string?

My controller method looks like this:

public ActionResult SomeMethod(Dictionary<int, string> model)
{

}

Is it possible to call this method and populate "model" using only query string? I mean, typing something like this:

ControllerName/SomeMethod?model.0=someText&model.1=someOtherText

in our browser address bar. Is it possible?

EDIT:

It would appear my question was misunderstood - I want to bind the query string, so that the Dictionary method parameter is populated automatically. In other words - I don't want to manually create the dictionary inside my method, but have some automathic .NET binder do it form me, so I can access it right away like this:

public ActionResult SomeMethod(Dictionary<int, string> model)
{
    var a = model[SomeKey];
}

Is there an automatic binder, smart enough to do this?

like image 493
user2384366 Avatar asked Mar 28 '14 08:03

user2384366


2 Answers

In ASP.NET Core, you can use the following syntax (without needing a custom binder):

?dictionaryVariableName[KEY]=VALUE

Assuming you had this as your method:

public ActionResult SomeMethod([FromQuery] Dictionary<int, string> model)

And then called the following URL:

?model[0]=firstString&model[1]=secondString

Your dictionary would then be automatically populated. With values:

(0, "firstString")
(1, "secondString")
like image 168
thebfactor Avatar answered Sep 19 '22 08:09

thebfactor


For .NET Core 2.1, you can do this very easily.

public class SomeController : ControllerBase
{
    public IActionResult Method([FromQuery]IDictionary<int, string> query)
    {
        // Do something
    }
}

And the url

/Some/Method?1=value1&2=value2&3=value3

It will bind that to the dictionary. You don't even have to use the parameter name query.

like image 30
Todd Skelton Avatar answered Sep 19 '22 08:09

Todd Skelton