我正在创建一个可重用的方法来检查我的模型并自动构建URL(通过ActionLink
)进行分页。我的模型上的一个属性是string[]
(对于多选选择列表),它完全有效。 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();
当需要多次使用密钥时,我可以使用什么来构建路由?
答案 0 :(得分:7)
您只需要将属性名称与索引器一起指定为Key
:
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]);
}
}
答案 1 :(得分:4)
试着想象链接的外观和它应该有意义
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