asp.net-mvc – 向RouteValueDictionary添加复杂类型的数组

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 向RouteValueDictionary添加复杂类型的数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否有一种优雅的方法可以将一组复杂类型添加到RouteValueDictionary或兼容类型?

例如,如果我有一个类和一个动作:

  1. public class TestObject
  2. {
  3. public string Name { get; set; }
  4. public int Count { get; set; }
  5.  
  6. public TestObject()
  7. {
  8. }
  9.  
  10. public TestObject(string name,int count)
  11. {
  12. this.Name = name;
  13. this.Count = count;
  14. }
  15. }
  16.  
  17. public ActionResult Test(ICollection<TestObjects> t)
  18. {
  19. return View();
  20. }

然后我知道如果我通过URL调用此操作“/Test?t[0].Name=One\u0026amp;t[0].Count=1\u0026amp;t[1].Name=Two\u0026amp;t[1].Count= 2“MVC会自动将这些查询字符串参数映射回ICollection类型.但是,如果我使用Url.Action()在某处手动创建链接,并且我想传递参数的RouteValueDictionary,当我向RouteValueDictionary添加ICollection时,Url.Action只是将其呈现为类型,如& T = System.Collections.Generic.List.

例如:

  1. RouteValueDictionary routeValDict = new RouteValueDictionary();
  2. List<TestObject> testObjects = new List<TestObject>();
  3.  
  4. testObjects.Add(new TestObject("One",1));
  5. testObjects.Add(new TestObject("Two",2));
  6. routeValDict.Add("t",testObjects);
  7.  
  8. // Does not properly create the parameters for the List<TestObject> collection.
  9. string url = Url.Action("Test","Test",routeValDict);

有没有办法让它自动将该集合呈现为MVC也理解如何映射的格式,或者我必须手动执行此操作?

我错过了什么,为什么他们会这样做,所以这个美丽的映射存在于一个Action中,但没有提供一种手动反向创建URL的方法

解决方法

我也遇到了这个问题,并使用了Zack的代码,但发现了一个错误.如果IEnumerable是一个字符串数组(string []),则存在问题.所以我认为我会分享我的扩展版本.
  1. public static RouteValueDictionary ToRouteValueDictionaryWithCollection(this RouteValueDictionary routeValues)
  2. {
  3. var newRouteValues = new RouteValueDictionary();
  4.  
  5. foreach(var key in routeValues.Keys)
  6. {
  7. object value = routeValues[key];
  8.  
  9. if(value is IEnumerable && !(value is string))
  10. {
  11. int index = 0;
  12. foreach(object val in (IEnumerable)value)
  13. {
  14. if(val is string || val.GetType().IsPrimitive)
  15. {
  16. newRouteValues.Add(String.Format("{0}[{1}]",key,index),val);
  17. }
  18. else
  19. {
  20. var properties = val.GetType().GetProperties();
  21. foreach(var propInfo in properties)
  22. {
  23. newRouteValues.Add(
  24. String.Format("{0}[{1}].{2}",index,propInfo.Name),propInfo.GetValue(val));
  25. }
  26. }
  27. index++;
  28. }
  29. }
  30. else
  31. {
  32. newRouteValues.Add(key,value);
  33. }
  34. }
  35.  
  36. return newRouteValues;
  37. }

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