I have a view that contains a Twitter Bootstrap nav nav-pills control. This is embedded fine, and in each of my tabs I am planning to embed two partial views. Below is the razor view

@using SiteNET.Models;
@using Microsoft.AspNet.Identity;
@model SiteNET.Models.ManageUserViewModel
@{
    ViewBag.Title = "Manage Account";
}
<style type="text/css">
    .manage {
        margin: 20px;
    }
</style>
<div class="manage">
    <ul class="nav nav-pills" id="myTab">
        <li><a data-toggle="tab" href="#manage">Manage Account</a></li>
        <li><a data-toggle="tab" href="#downloads">Avalible Downloads</a></li>
    </ul>
    <div class="tab-content">
        <div id="manage" class="tab-pane active fade in">
            <h2>@ViewBag.Title</h2>
            <p class="text-success">@ViewBag.StatusMessage</p>
            @*<div class="alert alert-success"
            data-toggle="collapse"
            role="alert">@ViewBag.StatusMessage</div>*@
            <div class="row">
                <div class="col-md-12">
                    @Html.Partial("_ChangeEmailAddressPartial", Model)
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    @if (ViewBag.HasLocalPassword)
                    {
                        @Html.Partial("_ChangePasswordPartial")
                    }
                    else
                    {
                        @Html.Partial("_SetPasswordPartial")
                    }
                </div>
            </div>
            @section Scripts {
                @Scripts.Render("~/bundles/jqueryval")
            }
        </div>
        <div id="downloads" class="tab-pane fade">
            <h3>Downloads</h3>
            <p>Avalible downloads partial view.</p>
        </div>
    </div>
</div>

The problem is that when the page loads the content of the first tab is shown but the actual tab is not selected (see below)

Not Selected First Tab

it should look like this when the page is first loaded

How it Should Look

I have tried to use this solution, which uses the JavaScript below

<script>
    $('#myTab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    // Store the currently selected tab in the hash value
    $("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
        var id = $(e.target).attr("href").substr(1);
        window.location.hash = id;
    });

    // On load of the page: switch to the currently selected tab
    var hash = window.location.hash;
    $('#myTab a[href="' + hash + '"]').tab('show');
</script>

But this does not seem to work (that is, does not seem to select the first tab when the page is loaded). It also does not store the selected tab. How can I

  1. Make the first tab show as selected when the page is first loaded?
  2. How can I amend the JS above so that the selected tab is persisted between page navigations?

Thanks for your time.

Related posts

Recent Viewed