本文介绍了将QueryString解析为强类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道它可以自动完成;
I know it can be done automatically;
class Query
{
public int?[] Id { get; set; }
}
public ActionResult Index(Query q)
{
}
一些QueryString /index?id = 10& id = 11
Some QueryString /index?id=10&id=11
它完美无瑕.
但是在某些情况下,我只有可用的请求:
But in some scenario I have only request available:
Reqest.RawUrl
是否可以使用内置解析来创建查询对象?
It is possible to use built-in parsing to create query object?
Query q = SomeMagicStuff<Query>(Request.RawUrl);
推荐答案
是可以的.如果您使用MVC,则可以使用MVC DefaultModelBinder
,我为这种情况编写了一个函数:
Yes it is possible. If you using MVC you can use MVC DefaultModelBinder
i write a function for this case:
public class MyModelBinder<T>
{
private ModelBindingContext modelBindingContext = new ModelBindingContext();
/// <summary>
/// Method to get model from QueryString
/// </summary>
/// <param name="request">HttpRequest</param>
/// <returns>T model</returns>
public static T GetModelFromQueryString(HttpRequest request)
{
modelBindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));
modelBindingContext.ValueProvider = new NameValueCollectionValueProvider(request.QueryString, System.Globalization.CultureInfo.InvariantCulture);
IModelBinder mb = new DefaultModelBinder();
return (T)mb.BindModel(new ControllerContext(), modelBindingContext);
}
/// <summary>
/// Method to get model from FormColletion
/// </summary>
/// <param name="request">HttpRequest</param>
/// <returns>T model</returns>
public static T GetModelFromFormColletion(HttpRequest request)
{
modelBindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));
modelBindingContext.ValueProvider = new NameValueCollectionValueProvider(request.Params, System.Globalization.CultureInfo.InvariantCulture);
IModelBinder mb = new DefaultModelBinder();
return (T)mb.BindModel(new ControllerContext(), modelBindingContext);
}
}
请注意,有2种方法.它们仅在 request.Params
和 request.QueryString
上有所不同.
Note that there is 2 methods. They are differ only with request.Params
and request.QueryString
.
这篇关于将QueryString解析为强类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!