MVC QueryString转换为动态对象 [英] MVC QueryString into Dynamic Object
问题描述
是否可以使用查询字符串参数填充动态对象?
Is there a way to populate a Dynamic object with Query String parameters?
这样一来,我的QS中的搜索参数就可以改变,而不必直接将它们绑定到容器对象上,也不必更改搜索方法的签名.
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.
例如
入站URL:www.test.com/Home/Search?name=john&product=car&type=open&type=all
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);
}
填充的searchParams对象应如下所示:
The populated searchParams object should look like:
{
name = "john",
product = "car",
type = { "open", "all" }
}
有什么想法吗?
推荐答案
一个解决方案可以是建立 Request.QueryString ,它是 NameValueCollection .
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);
}
注意:您将需要执行一些其他转换以处理type
属性,默认情况下该属性不会自动成为数组.
Note: You will need to do some additional transformation to handle to type
property which won't be automatically an array by default.
这篇关于MVC QueryString转换为动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!