Select Tab on Page Load in ASP.NET MVC

MoonKnight picture MoonKnight · Nov 12, 2015 · Viewed 8.1k times · Source

I have two tabs on a Razor page, I want to be able to load the page and either select page A or B. Currently, the page loads and always lands on A. I have attempted to do this as follows...

In my home view I call my products view

<a class="btn btn-default"
   href='@Url.Action("Index", "Products", new { id = "productB" })'
   role="button">
   Learn More 
</a>

where I am passing the route value "productB" so I can attempt to load the tab. In my products controller I have

public ActionResult Index(object id = null)
{
    if (id != null && !String.IsNullOrEmpty())
        ViewBag.ActiveTab = id.ToString();
    return View();
}

products view

@{
    string activeTab = ViewBag.ActiveTab;
}

<div class="products container">
    <ul class="nav nav-tabs">
        <li class="active">
            <a data-toggle="tab" href="#productA">
                <span class="glyphicon glyphicon glyphicon-plus-sign"></span>productA
            </a>
        </li>
        <li>
            <a data-toggle="tab" href="#productB">
                <span class="glyphicon glyphicon glyphicon-align-left"></span>productB
            </a>
        </li>
    </ul>
    <div class="products-body">
        <div class="tab-content">
            <div id="productA" class="tab-pane active fade in">
                ...
            </div>
            <div id="productB" class="tab-pane fade">
                ...
            </div>
        </div>
    </div>
</div>

with the function

$(function () {
    var selector = '@activeTab';
    $("#" + selector).addClass("active");

    // Also tried the following...
    // var anchor = '@activeTab' || $("a[data-toggle=tab]").first().attr("href");
    // $('a[href=' + anchor + ']').tab('show');
});

But this does not select my tab page. This seems so simple, how can I get this to work?

Answer

davcs86 picture davcs86 · Nov 12, 2015

Try

$(function () {
    var anchor = "@Html.Raw(HttpUtility.JavaScriptStringEncode(activeTab))"
        || $(".nav-tabs a").first().attr("href").replace('#','');
    //$('#'+anchor).tab('show');
    $('.nav-tabs a[href=#' + anchor + ']').tab('show');
});

Also ensure that you have activated the tabs

$('.nav-tabs a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
})

JSFiddle demo