Asp.net mvc 当路由具有多个值时,如何构建RouteValueDictionary?
我正在创建一个可重用的方法,用于检查我的模型并自动构建用于分页的URL(通过Asp.net mvc 当路由具有多个值时,如何构建RouteValueDictionary?,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing,Asp.net Mvc,Asp.net Mvc 5,Asp.net Mvc Routing,我正在创建一个可重用的方法,用于检查我的模型并自动构建用于分页的URL(通过ActionLink)。我的模型上的一个属性是一个完全有效的字符串[](对于多选拾取列表)。URL的一个示例是:https://example.com?user=Justin&user=John&user=Sally 但是,正如类型名称所示,RouteValueDictionary实现了IDictionary,因此它不能多次接受同一个键 var modelType = model.GetType(); var route
ActionLink
)。我的模型上的一个属性是一个完全有效的字符串[]
(对于多选拾取列表)。URL的一个示例是:https://example.com?user=Justin&user=John&user=Sally
但是,正如类型名称所示,RouteValueDictionary
实现了IDictionary
,因此它不能多次接受同一个键
var modelType = model.GetType();
var routeProperties = modelType.GetProperties().Where(p => Attribute.IsDefined(p, typeof(PagingRouteProperty)));
if (routeProperties != null && routeProperties.Count() > 0) {
foreach (var routeProperty in routeProperties) {
if (routeProperty.PropertyType == typeof(String)) {
routeDictionary.Add(routeProperty.Name, routeProperty.GetValue(model, null));
}
if (routeProperty.PropertyType == typeof(Boolean?)) {
var value = (Boolean?)routeProperty.GetValue(model, null);
routeDictionary.Add(routeProperty.Name, value.ToString());
}
//The problem occurs here!
if (routeProperty.PropertyType == typeof(string[])) {
var value = (string[])routeProperty.GetValue(model);
foreach (var v in value) {
routeDictionary.Add(routeProperty.Name, v);
}
}
}
//Eventually used here
var firstPageRouteDictionary = new RouteValueDictionary(routeDictionary);
firstPageRouteDictionary.Add("page", 1);
firstPageListItem.InnerHtml = htmlHelper.ActionLink("«", action, controller, firstPageRouteDictionary, null).ToHtmlString();
当一个密钥被多次需要时,我可以用什么来构建路由呢?试着想象一下链接的外观和意义
new RouteValueDictionary { { "name[0]", "Justin" }, { "name[1]", "John" }, { "name[2]", "Sally" } }
将生成以下查询字符串
编码的
?name%5B0%5D=Justin&name%5B1%5D=John&name%5B3%5D=Sally
解码
?name[0]=Justin&name[1]=John&name[3]=Sally
您只需将属性名和索引器一起指定为
键
:
if (routeProperty.PropertyType == typeof(string[])) {
var value = (string[])routeProperty.GetValue(model);
for (var i = 0; i < value.Length; i++) {
var k = String.Format("{0}[{1}]", routeProperty.Name, i);
routeDictionary.Add(k, value[i]);
}
}
if(routeProperty.PropertyType==typeof(string[])){
var value=(字符串[])routeProperty.GetValue(模型);
对于(变量i=0;i
常规医疗的类型是什么?这是普通的RouteValueDictionary
?对不起,我应该包括在内。你说得对!