0


I am using Bootstrap ScrollSpy in MVC 5 application.
ScrollSpy works fine with plain html and jquery but I want to implement the same thing in MVC 5.

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

the above code works fine, but when I tried to implement the same thing in MVC I somehow get confused.

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

This is not working as expected as its trying to redirect to specified actionname or I may be doing something wrong.
Suggest something.

2 Answers2

1

Requirement for Bootstrap scrollspy to work, the scrollable elements must match the ID of the links.

Here <li><a href="#contact" class="hidden-xs">Contact</a></li> should match div with id <div id="contact">

Using Mvc:

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

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

Check difference between HTML.ActionLink vs Url.Action here.

So finally in server side both generates url with trailing slash before hash(#) as shown below:

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

And thus above link doesn't match div with id <div id="contact"> because of / before #

Solution Using Mvc:

Create Custom UrlHelper

Create a folder named Helpers and add a class named UrlExtensions finally add below code:

public static class UrlExtensions
{

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

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

     return hashAnchorLink;

    }

}

In View:

@using YourProjectName.Helpers;

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

Note:

Best solution would be using plain html as you did before, instead of using server to return the hash link.

References:

1.

2.

3.

Shaiju T
  • 6,201
  • 20
  • 104
  • 196
0

Your not passing the right parameters in into the 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.

dev8989
  • 339
  • 1
  • 3
  • 15
  • Hi, I think you have not got the question yet.i am facing issue while working with bootstrap scrollspy in MVC. How to write the actionlink function to get the scrollspy work. – Amey Deshpande Dec 27 '17 at 06:10