在 MVC 5 中使用 bootstrap scrollspy

working with bootstrap scrollspy in MVC 5


我在 MVC 5 应用程序中使用 Bootstrap ScrollSpy。
ScrollSpy 在普通 html 和 jquery 上工作正常,但我想在 MVC 5 中实现同样的事情。

<li><a href="#about" class="hidden-xs">About</a></li>
<li><a href="#contact" class="hidden-xs">Contact</a></li>

上面的代码工作正常,但是当我试图在 MVC 中实现同样的东西时,我不知何故感到困惑。

<li> @Html.ActionLink("About", null, null, null, new { @class = "hidden-xs" })</li>
<li> @Html.ActionLink("Contact", null,null, null, new { @class = "hidden-xs" })</li>

这没有按预期工作,因为它试图重定向到指定的操作名称,或者我可能做错了什么。
提点建议。

您没有将正确的参数传递到 ActionLink()

@Html.ActionLink("About", "Home", "About", new object { }, new { @class = "hidden-xs"})
@Html.ActionLink("Contact", "Home", "Contact", new object { }, new { @class = "hidden-xs"})

Here is a explanation of the function.

Bootstrap scrollspy 工作的要求,可滚动元素必须与 link 的 ID 相匹配。

此处 <li><a href="#contact" class="hidden-xs">Contact</a></li> 应与 ID <div id="contact">

匹配 div

使用 Mvc:

<li> @Html.ActionLink("Contact", "Index", "Home", null, null, "contact", null, null)</li>

<li> <a href="@Url.Action("Index", "Home")#contact">Contact</a></li>

检查 HTML.ActionLinkUrl.Action here 之间的差异。

所以最后在服务器端都生成 url,在 hash(#) 之前带有斜杠,如下所示:

<a href="/#contact">Contact</a>

因此上面的 link 与 ID <div id="contact"> 不匹配 div 因为 /#

之前

使用 Mvc 的解决方案:

创建自定义 UrlHelper

创建一个名为 Helpers 的文件夹并添加一个名为 UrlExtensions 的 class 最后添加以下代码:

public static class UrlExtensions
{

    public static string HashAnchorLinks(this UrlHelper url, string hashLinkName)
    {

     string hashAnchorLink = string.Format("#{0}", hashLinkName);

     return hashAnchorLink;

    }

}

在视图中:

@using YourProjectName.Helpers;

<li> <a href="@Url.HashAnchorLinks("about")">About</a></li>
<li> <a href="@Url.HashAnchorLinks("contact")">Contact</a></li>

注:

最好的解决方案是像以前一样使用纯 html,而不是使用服务器 return 哈希 link.

参考文献:

1.

2.

3.