【问题标题】:How to build a RouteValueDictionary when a route has multiple values?当路由有多个值时如何构建 RouteValueDictionary?
【发布时间】: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


【解决方案1】:

您只需将属性名称与索引器一起指定为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]);
    }
}

【讨论】:

    【解决方案2】:

    试着想象一下链接的外观,它应该是有意义的

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多