我需要生成此网址: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");
获取:已添加具有相同键的项目
甚至
routeData.Add("GroupId[0]", "1");
routeData.Add("GroupId[1]", "2");
获取:?GroupId%5B0%5D=1&GroupId%5B1%5D=2
有可能以某种方式解决我的问题吗?
答案 0 :(得分:1)
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();
}
此函数将构建路径的完整路径,并将additionalParams对象中的值作为查询字符串数据附加。这可以通过执行ToString方法来处理数组,枚举,可空值和其他类型。
希望这有帮助!