gpt4 book ai didi

asp.net-mvc-3 - 如何将 int 数组传递给 RouteValueDictionary

转载 作者:行者123 更新时间:2023-12-02 05:28:16 26 4
gpt4 key购买 nike

我需要生成此网址:http://localhost:3178/Reports/?GroupId=1211&GroupId=1237

我正在尝试:

var routeData = new RouteValueDictionary();
routeData.Add("GroupId", "1, 2");

获取:GroupId=1,%202

routeData.Add("GroupId", "1");
routeData.Add("GroupId", "2");

获取:已添加具有相同 key 的项目

甚至

routeData.Add("GroupId[0]", "1");
routeData.Add("GroupId[1]", "2");

获取:?GroupId%5B0%5D=1&GroupId%5B1%5D=2

有可能以某种方式解决我的问题吗?

最佳答案

RouteValueDictionary 旨在为路由提供信息。因此,我认为它不具备您所要求的功能。我一直在使用自定义助手根据我传递给它的内容来填充查询字符串数据:

    public static string BuildPath(RequestContext context, string routeName, RouteValueDictionary routeValues, object additionalParams)
{
var vpd = RouteTable.Routes[routeName].GetVirtualPath(context, routeValues);

if (vpd == null)
return string.Empty;

var virtualpath = vpd.VirtualPath;
var addparams = BuildAdditionalParams(additionalParams);

if (!virtualpath.Contains("?") && addparams.Length > 0)
virtualpath = virtualpath + "?" + addparams;
else if (virtualpath.Contains("?") && addparams.Length > 0)
virtualpath = virtualpath + "&" + addparams;

return "/" + virtualpath;
}

protected static string BuildAdditionalParams(object additionalParams)
{
if (additionalParams == null)
return string.Empty;

StringBuilder sb = new StringBuilder();
Type type = additionalParams.GetType();
PropertyInfo[] props = type.GetProperties();

Action<string, string> addProperty = (name, value) =>
{
if (sb.Length > 0)
sb.Append("&");
sb.Append(name);
sb.Append("=");
sb.Append(value);
};

foreach (PropertyInfo prop in props)
{
var simplevalue = prop.GetValue(additionalParams, null);
if (simplevalue != null)
{
Type propertyType = prop.PropertyType;
if (Nullable.GetUnderlyingType(propertyType) != null)
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}

if (propertyType.IsEnum)
{
addProperty(prop.Name, ((int)simplevalue).ToString());
}
else if (propertyType.IsArray && propertyType != typeof(string))
{
foreach (var val in prop.GetValue(additionalParams, null) as IEnumerable)
addProperty(prop.Name, val.ToString());
}
else
{
if (!string.IsNullOrEmpty(simplevalue.ToString()))
addProperty(prop.Name, simplevalue.ToString());
}
}
}
return sb.ToString();
}

此函数将构建路线的完整路径,并将附加参数对象中的值作为查询字符串数据附加。这可以通过执行 ToString 方法来处理数组、枚举、可为空值和其他类型。

希望这有帮助!

关于asp.net-mvc-3 - 如何将 int 数组传递给 RouteValueDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6396136/

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