Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC QueryString into Dynamic Object

Tags:

c#

asp.net-mvc

Is there a way to populate a Dynamic object with Query String parameters?

This is so that my search parameters in the QS can vary without binding them directly to a container object or having to change the signature of the search method.

e.g.

Inbound URL: www.test.com/Home/Search?name=john&product=car&type=open&type=all

public ActionResult Search()
{
    dynamic searchParams = // **something magic here**

    var model = getResults(searchParams);
    return View(model);
}

The populated searchParams object should look like:

{
    name = "john",
    product = "car",
    type = { "open", "all" }
}

Any ideas?

like image 845
Nick Avatar asked Jul 17 '12 09:07

Nick


1 Answers

One solution can be that you build up an ExpandoObject from the Request.QueryString which is a NameValueCollection.

It's easy to write the transformation and you can put it inside an extension method:

public static class NameValueCollectionExtensions:
{
    public static dynamic ToExpando(this NameValueCollection valueCollection)
    {
        var result = new ExpandoObject() as IDictionary<string, object>;
        foreach (var key in valueCollection.AllKeys)
        {
            result.Add(key, valueCollection[key]);
        }
        return result;
    }
}

And in your controller you can use like:

public ActionResult Search()
{
    dynamic searchParams = Request.QueryString.ToExpando();

    DoSomething(searchParams.name);  
    var model = getResults(searchParams);
    return View(model);
}

Note: You will need to do some additional transformation to handle to type property which won't be automatically an array by default.

like image 102
nemesv Avatar answered Sep 19 '22 01:09

nemesv