zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    MSSQLSERVER数据库 C#里调用存储过程,多参数查询,个人记录
    ASP.NET GridView和Repeater合并单元格
    C# XPath教程
    MSSQLSERVER数据库 导入文本文件
    MSSQLSERVER数据库 递归查询例子
    C# TreeView右键弹出菜单
    tomcat 下War包部署方法
    JAVA自定义标签教程及实例代码
    JAVA tag学习
    Java Quartz 自动调度
  • 原文地址:https://www.cnblogs.com/liuxiaoji/p/4519827.html
Copyright © 2011-2022 走看看