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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With