【问题标题】:Html.ActionLink with a specified HTML id?具有指定 HTML id 的 Html.ActionLink?
【发布时间】:2011-04-07 01:26:57
【问题描述】:

我想给用Html.ActionLink 生成的类似 HTML id,这样我就可以根据我所在的位置更改 CSS。我有一个带有一组链接的MasterPage,我想用 Jquery 来区分活动的“Tab”,改变该活动#id 的 css

我现在正在使用:

<%: Html.ActionLink("Some View", "Index", "controller")%>

它生成:

<a href="/controller">Some View</a>

我想生成:

<a id="something" href="/controller">Some View</a>

这可能吗?我试过了:

<%: Html.ActionLink("Some View", "Index", "controller", new {id="blahbla")%>

但这会产生:

<a href="/controller/Length?5">Some View</a>

【问题讨论】:

  • 我不熟悉正确的语法,但是{真的不应该被关闭吗?
  • 应该,但我原以为 Web 服务器在尝试运行该网页时会产生错误。我认为这是一个错字。请问楼主可以确认一下吗?

标签: css asp.net-mvc asp.net-mvc-2 html-helper actionlink


【解决方案1】:

你走在正确的轨道上。我不确定为什么它对您不起作用,因为您的代码有错字,会产生} expected 错误。以下是您要查找的内容:

 <%= Html.ActionLink("Test Link", "SomeAction", "SomeController",
         null, new {id = "someID" }) %> 

这会产生以下 HTML:

<a href="/SomeController/SomeAction" id="someID">Test Link</a>

编辑:我刚刚意识到问题出在哪里,因为我误读了您尝试的内容。您使用了错误的重载来传递 id html 元素。您可能将new { id="blah" } 参数传递给routeValues 参数,这将导致在构建路由链接时使用它,而不是您想要的htmlAttributes 参数。

我认为你正在使用:

ActionLink(string linkText, string actionName, Object routeValues,
    Object htmlAttributes)

当您需要使用以下重载时,就像我在上面的回答中所做的那样:

ActionLink(string linkText, string actionName, string controllerName,
    Object routeValues, Object htmlAttributes)

确保new { id="blah" } 被传递到htmlAttributes 参数中。

【讨论】:

    【解决方案2】:

    试试这个:

    <%: Html.ActionLink("Some View", "Index", "controller", null, new {id="something}")%>
    

    【讨论】:

      【解决方案3】:

      基本上它给出了一个错误,因为没有具有您想要的签名的方法重载。

      最接近您需要的签名是

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

      )

      您正在将 id 属性传递给 routevalue,这就是它为您提供有趣 href 的原因。将 null 传递给 routevalue,然后添加您的 htmlattributes

      【讨论】:

        【解决方案4】:

        试试这个

        @Html.ActionLink("Forgot your access?", "RecoverPassword", 
        "Account", new { area = "registration-full.html" }, 
        new { @class = "col-xs-6", id = "login-forget-link" })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-12-12
          • 2016-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多