gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:30:46 26 4
gpt4 key购买 nike

我正在创建一个可重用的方法来检查我的模型并自动构建 URL(通过 ActionLink)进行分页。我的模型的属性之一是 string[] (对于多选选择列表)这是完全有效的。 URL 的一个例子是:https://example.com?user=Justin&user=John&user=Sally .

但是,正如类型名称所暗示的那样,RouteValueDictionary工具IDictionary所以它不能多次接受相同的 key 。

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 时,我可以使用什么来构建路线?

最佳答案

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

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

关于asp.net-mvc - 当路由具有多个值时如何构建 RouteValueDictionary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27383705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com