AJAX and Bootstrap Tabbing in MVC

In this tutorial you will see the Twitter Bootstrap tabstrip in action. I will be using MVC, Razor and jQuery to accomplish this. If you visit the tabstrip documentation you will see an example that uses static tab content. I have expanded upon that code snippet, converting it to dynamic content using AJAX. I’m also utilizing a fading transition effect as the content loads. The tabstrip will interact with two partial views named: _SearchTab.cshtml and _SubmissionTab.cshtml. Notice that I am naming the tab ids the same as the partial views. Doing that reduces translation in the script when relaying the AJAX calls.

Markup:

The @Html.Partial will request the page on the active tab on page load. Place this call wherever the active class is being set.

Script:

The $.ajax() request retrieves the partial view. The cache parameter is necessary to ensure a fresh rebuild on each click. As for what path is requested you will notice a @ViewContext.RouteData.Values["controller"] call. It simply retrieves the controller of the current view, assuming the partial views are located in the same folder in the tree.

Controller:

The above methods are needed to relay the $.ajax() request to the proper partial view.

Now each time you click on a tab it will load dynamic content from a partial view. Keeping content separate can keep code cleaner and more organized. Download an example implementing this technique.