MVC QueryString in a dynamic object

Is there a way to populate a dynamic object with query string parameters?

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

eg.

Incoming 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 this:

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

Any ideas?

+5
source share
3 answers

One solution could be to create an ExpandoObject from Request.QueryString , which is a NameValueCollection .

It is easy to write a transformation, and you can put it in 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;
    }
}

:

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

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

. type , .

+9

-

dynamic searchParams = new
            {
                name = "john",
                product = "car",
                type = new {aa =  "open", bb = "all"}
            };

.

0

I would rather use a dynamic object and do the following:

public class QSValues : DynamicObject
    {
        readonly Dictionary<string, object> dynamicProperties = new Dictionary<string, object>();

        public string ErrorMessage { get; set; }

        public bool IsSuccessful { get; set; }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            dynamicProperties[binder.Name] = value;

            return true;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return dynamicProperties.TryGetValue(binder.Name, out result);
        }

and then parse the QueryString parameters

0
source

All Articles