【问题标题】:working with bootstrap scrollspy in MVC 5在 MVC 5 中使用 bootstrap scrollspy
【发布时间】:2018-06-07 16:47:40
【问题描述】:


我在 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>

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

【问题讨论】:

  • 您使用的是 Bootstrap 3.3.7 版吗?
  • 我正在使用 bootstrap v 3.0.0,这是您在 Visual Studio 中创建项目模板时的默认设置。
  • 您只需要使用@Html.ActionLink 的解决方案吗?因为有几个问题需要克服,比如你必须改变路线等,所以我应该使用@Url.Action 提供解决方案吗?
  • 当然。您也可以使用 uri.Action 提供解决方案。
  • 如果可能的话,也尝试分享一下我们为什么不能在这里使用 html.ActionLink 的发现。这会很有帮助,因为我正处于 MVC 的学习阶段

标签: asp.net-mvc twitter-bootstrap scrollspy


【解决方案1】:

Bootstrapscrollspy 工作的要求,可滚动元素必须与链接的 ID 匹配。

这里&lt;li&gt;&lt;a href="#contact" class="hidden-xs"&gt;Contact&lt;/a&gt;&lt;/li&gt;应该匹配id为&lt;div id="contact"&gt;的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>

因此,上面的链接与 id 为 &lt;div id="contact"&gt; 的 div 不匹配,因为 /# 之前

使用 Mvc 的解决方案:

创建自定义UrlHelper

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

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,而不是使用服务器返回哈希链接。

参考资料:

1.

2.

3.

【讨论】:

    【解决方案2】:

    您没有将正确的参数传递给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.

    【讨论】:

    • 嗨,我想你还没有得到这个问题。我在 MVC 中使用 bootstrap scrollspy 时遇到了问题。如何编写 actionlink 函数来获得 scrollspy 工作。
    猜你喜欢
    • 2021-01-17
    • 2019-01-15
    • 1970-01-01
    • 2013-08-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    相关资源
    最近更新 更多