我在MVC 5应用程序中使用bootstrap scrollspy。
ScrollSpy可以与Plain 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>
这并不能像试图重定向到指定的ActionName那样工作,或者我可能做错了。
建议一些东西。
Bootstrap
scrollspy
的要求,可滚动元素必须匹配链接的ID。
在这里<li><a href="#contact" class="hidden-xs">Contact</a></li>
应与ID <div id="contact">
使用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.ActionLink
与Url.Action
之间的差异。
因此,最终在服务器端都在hash(#)
之前生成url
,如下所示:
<a href="/#contact">Contact</a>
因此,由于#
/
,链接上的链接与ID <div id="contact">
不匹配使用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。
您没有将正确的参数传递到ActionLink()
中。
@Html.ActionLink("About", "Home", "About", new object { }, new { @class = "hidden-xs"})
@Html.ActionLink("Contact", "Home", "Contact", new object { }, new { @class = "hidden-xs"})
这是对功能的解释。