【发布时间】:2014-12-09 16:17:21
【问题描述】:
我正在创建一个可重用的方法来检查我的模型并自动构建 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();
当多次需要一个键时,我可以使用什么来构建路由?
【问题讨论】:
-
routeDictionary的类型是什么?是正规的RouteValueDictionary吗? -
对不起,我应该把它包括在内。你是对的!
标签: asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing