[英]MVC QueryString into Dynamic Object
Is there a way to populate a Dynamic object with Query String parameters? 有没有办法用Query String参数填充Dynamic对象?
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. 这样我的QS中的搜索参数可以变化而不会将它们直接绑定到容器对象或者必须更改搜索方法的签名。
eg 例如
Inbound URL: www.test.com/Home/Search?name=john&product=car&type=open&type=all 入站网址: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: 填充的searchParams对象应如下所示:
{
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 . 一种解决方案可以是从Request.QueryString构建一个ExpandoObject ,它是一个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. 注意:您需要进行一些额外的转换来处理type
属性,默认情况下它不会自动成为数组。
Something like this would do the trick 像这样的东西可以解决问题
dynamic searchParams = new
{
name = "john",
product = "car",
type = new {aa = "open", bb = "all"}
};
Swapping out the strings for your query string values. 替换查询字符串值的字符串。
I would rather use dynamic object and do 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 QueryString parameters 然后解析QueryString参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.