【问题标题】:Asp.Net MVC ActionLinkAsp.Net MVC 动作链接
【发布时间】:2010-05-24 13:56:21
【问题描述】:

谁能解释为什么会发生以下情况?以及如何解决,Visual Studio 2010 和 MVC2

<%= Html.ActionLink("Add New Option", "AddOption", "Product", new { @class = "lighbox" }, null)%>

结果

/Product/AddOption?class=灯箱

<%= Html.ActionLink("Add New Option", "AddOption", "Product", new { @class = "lighbox" })%>

结果

/Product/AddOption?Length=7

谢谢

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-2 extension-methods


    【解决方案1】:

    您正在使用这些各自的重载:

    public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
    )
    

    发件人:http://msdn.microsoft.com/en-us/library/dd504972.aspx

    public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    Object routeValues,
    Object htmlAttributes
    )
    

    发件人:http://msdn.microsoft.com/en-us/library/dd492124.aspx

    当第一个 new { @class = "lighbox" } 应该是 htmlAttributes 参数时,它作为 routeValues 参数传递。

    这类问题在 MVC 中使用的扩展方法中很常见。 In 有时可以帮助使用 命名参数 (C# 4.0) 使内容更具可读性:

    <%= Html.ActionLink(linkText: "Add New Option", 
       actionName: "AddOption",
       controllerName: "Product", 
       htmlAttributes: new { @class = "lighbox" }, 
       routeValues: null)%>
    

    【讨论】:

      【解决方案2】:

      这是 ASP.NET MVC 中的“重载地狱”示例。

      第一段代码调用如下方法:

      public static MvcHtmlString ActionLink(
          this HtmlHelper htmlHelper,
          string linkText,
          string actionName,
          string controllerName,
          Object routeValues,
          Object htmlAttributes
      )
      

      而第二个代码调用这个:

      public static MvcHtmlString ActionLink(
          this HtmlHelper htmlHelper,
          string linkText,
          string actionName,
          Object routeValues,
          Object htmlAttributes
      )
      

      请注意,第一次调用中的字符串参数controllerName 在第二次调用中变为routeValues。字符串值“Product”被传递给路由值:使用了字符串属性Length,这里的长度为 7,因此您在路由中获得了“Length=7”。

      考虑到第一种方法,您似乎已经交换了routeValueshtmlAttributes 参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-26
        • 1970-01-01
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 2022-10-02
        相关资源
        最近更新 更多