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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 如何将int数组传递给RouteValueDictionary前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要生成这个URL:http:// localhost:3178 / Reports /?GroupId = 1211& GroupId = 1237

我尝试着:

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

得到:GroupId = 1,2

要么

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

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

乃至

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

得到:?GroupId [0] = 1& GroupId [1] = 2

有可能以某种方式修复我的问题?

解决方法

RouteValueDictionary旨在为路由提供信息.因此,我认为它没有你所要求的能力.我一直在使用自定义帮助器根据我传入的内容填充查询字符串数据:
  1. public static string BuildPath(RequestContext context,string routeName,RouteValueDictionary routeValues,object additionalParams)
  2. {
  3. var vpd = RouteTable.Routes[routeName].GetVirtualPath(context,routeValues);
  4.  
  5. if (vpd == null)
  6. return string.Empty;
  7.  
  8. var virtualpath = vpd.VirtualPath;
  9. var addparams = BuildAdditionalParams(additionalParams);
  10.  
  11. if (!virtualpath.Contains("?") && addparams.Length > 0)
  12. virtualpath = virtualpath + "?" + addparams;
  13. else if (virtualpath.Contains("?") && addparams.Length > 0)
  14. virtualpath = virtualpath + "&" + addparams;
  15.  
  16. return "/" + virtualpath;
  17. }
  18.  
  19. protected static string BuildAdditionalParams(object additionalParams)
  20. {
  21. if (additionalParams == null)
  22. return string.Empty;
  23.  
  24. StringBuilder sb = new StringBuilder();
  25. Type type = additionalParams.GetType();
  26. PropertyInfo[] props = type.GetProperties();
  27.  
  28. Action<string,string> addProperty = (name,value) =>
  29. {
  30. if (sb.Length > 0)
  31. sb.Append("&");
  32. sb.Append(name);
  33. sb.Append("=");
  34. sb.Append(value);
  35. };
  36.  
  37. foreach (PropertyInfo prop in props)
  38. {
  39. var simplevalue = prop.GetValue(additionalParams,null);
  40. if (simplevalue != null)
  41. {
  42. Type propertyType = prop.PropertyType;
  43. if (Nullable.GetUnderlyingType(propertyType) != null)
  44. {
  45. propertyType = Nullable.GetUnderlyingType(propertyType);
  46. }
  47.  
  48. if (propertyType.IsEnum)
  49. {
  50. addProperty(prop.Name,((int)simplevalue).ToString());
  51. }
  52. else if (propertyType.IsArray && propertyType != typeof(string))
  53. {
  54. foreach (var val in prop.GetValue(additionalParams,null) as IEnumerable)
  55. addProperty(prop.Name,val.ToString());
  56. }
  57. else
  58. {
  59. if (!string.IsNullOrEmpty(simplevalue.ToString()))
  60. addProperty(prop.Name,simplevalue.ToString());
  61. }
  62. }
  63. }
  64. return sb.ToString();
  65. }

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

希望这可以帮助!

猜你在找的asp.Net相关文章