代码之家  ›  专栏  ›  技术社区  ›  LiamB

ASP.NET MVC操作链接

  •  10
  • LiamB  · 技术社区  · 15 年前

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

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

    结果在

    /产品/添加选项?类=灯箱

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

    结果在

    /产品/添加选项?长度=7

    谢谢

    2 回复  |  直到 15 年前
        1
  •  20
  •   David Neale    15 年前

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

    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" } 被作为 routeValues 当它应该是 htmlAttributes 争论。

    这种问题在MVC中使用的扩展方法中很常见。有时有助于使用 命名参数 (C 4.0)使事物更易读:

    <%= Html.ActionLink(linkText: "Add New Option", 
       actionName: "AddOption",
       controllerName: "Product", 
       htmlAttributes: new { @class = "lighbox" }, 
       routeValues: null)%>
    
        2
  •  9
  •   Julien Lebosquain    15 年前

    这是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”正在传递给路由值:string属性 Length 使用,这里的长度为7,因此您进入路线的“长度=7”。

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