【问题标题】:Use Anchor using Html.MenuLink asp.net mvc4使用 Anchor 使用 Html.MenuLink asp.net mvc4
【发布时间】:2014-03-03 23:32:37
【问题描述】:

我正在使用 Asp.net MVC4,我试图在 Html.MenuLink 中添加一个“锚”而不重写新的 MenuLink

这是我的html链接

<li class="nousjoindre">
    @Html.MenuLink("Join us", "Index", "JoinUs", null, new { @class = "active" })
</li>

渲染时生成这个html

<li class="join">
    <a href="/JoinUs">Join us</a>
</li>

和目标锚

<div>
    <h1 id="PointHere">Point here</h1>
</div>

和 MenuLink 代码

public static MvcHtmlString MenuLink( this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues = null, object htmlAttributes = null) 
{
    string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
    string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

    if (controllerName == currentController)
    {
        if (htmlAttributes == null) 
            htmlAttributes = new { @class = "selected" };

        return htmlHelper.ActionLink(
            linkText,
            actionName,
            controllerName,
            routeValues,
            htmlAttributes
        );
    }

    return htmlHelper.ActionLink(linkText, actionName, controllerName);
}

Html.MenuLink 的第 4 个参数用于向目标链接添加参数,但这不是我需要的。

我想要一个像localhost/JoinUs#PointHere这样的网址

感谢您的帮助

【问题讨论】:

  • 没有这样的Html.MenuLink ASP.NET MVC 4 内置助手。请附上您正在使用的自定义助手的相关源代码。
  • 对不起,我忘记了!!这里我包含了 MenuLink 代码

标签: c# html asp.net-mvc-4


【解决方案1】:

您可以使用 Html.ActionLink 帮助器的 following overload 生成带有片段标识符的 url:

return htmlHelper.ActionLink(
    linkText: linkText,
    actionName: actionName,
    controllerName: controllerName,
    protocol: null,
    hostName: null,
    fragment: "some_fragment",
    routeValues: routeValues,
    htmlAttributes: htmlAttributes
);

显然,您需要调整您的 MenuLink 自定义帮助程序,以将附加到 URL 的 fragment 标识符作为附加参数。

然后你就可以像这样调用它了:

@Html.MenuLink("Join us", "Index", "JoinUs", null, new { @class = "active" }, fragment: "PointHere")

【讨论】:

  • 完美运行。谢谢,这正是我需要的!
猜你喜欢
  • 2015-05-01
  • 2012-09-26
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多