MVC扩展Url.Action方法解决复杂对象参数问题

1:问题描述

  @Url.Action("Index", "Home", new { Key = "Key", Val = new { Name = "TypeDescriptor" } })

   期望结果: /Home/Index?Key=Key&Name=TypeDescriptor

   实际结果: /Home/Index?Key=Key

 

2.解决方案

  

 1         /// <summary>

 2         /// 递归算法

 3         /// </summary>

 4         /// <param name="dictionary">dictionary</param>

 5         /// <param name="values">values</param>

 6         public static void GetProperties(RouteValueDictionary dictionary, object values)

 7         {

 8             foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))

 9             {

10                 object obj = descriptor.GetValue(values);

11                 if (obj != null)

12                 {

13                     Type type = obj.GetType();

14                     if (!type.IsValueType && type != typeof(string))

15                     {

16                         GetProperties(dictionary, obj);

17                     }

18                     if (type.IsValueType || type == typeof(string))

19                     {

20                         if (dictionary.ContainsKey(descriptor.Name))

21                         {

22                             dictionary[descriptor.Name] = obj;

23                         }

24                         else

25                         {

26                             dictionary.Add(descriptor.Name, obj);

27                         }

28                     }

29                 }

30             }

31         }
递归算法获取参数列表
 1         /// <summary>

 2         /// Action

 3         /// </summary>

 4         /// <param name="urlHelper">urlHelper</param>

 5         /// <param name="actionName">actionName</param>

 6         /// <param name="controllerName">controllerName</param>

 7         /// <param name="routeValues">routeValues</param>

 8         /// <returns>string</returns>

 9         public static string Action(this UrlHelper urlHelper, string actionName, string controllerName, object routeValues)

10         {

11             RouteValueDictionary dictionary = new RouteValueDictionary();

12             GetProperties(dictionary, routeValues);

13             return UrlHelper.GenerateUrl(null, actionName, controllerName, dictionary, urlHelper.RouteCollection, urlHelper.RequestContext, true);

14         }
重写Action

 

你可能感兴趣的:(action)