加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 当路由有多个值时如何构建RouteValueDictionary

发布时间:2020-12-16 03:59:46 所属栏目:asp.Net 来源:网络整理
导读:我正在创建一个可重用的方法来检查我的模型并自动构建URL(通过ActionLink)进行分页.我的模型的一个属性是string [](对于多选选择列表),它完全有效. URL的示例如下:https://example.com?user = Justin user = John user = Sally. 但是,正如类型的名称所暗
我正在创建一个可重用的方法来检查我的模型并自动构建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();

当需要多次使用密钥时,我可以使用什么来构建路由?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读