Search code examples
asp.net-mvctwitter-bootstrapscrollspy

working with bootstrap scrollspy in MVC 5



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.


Solution

  • 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.