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:
1 2 3 4 5 6 7 8 9 10 11 |
<!-- Tab Buttons --> <ul id="tabstrip" class="nav nav-tabs" role="tablist"> <li class="active"><a href="#_SubmissionTab" role="tab" data-toggle="tab">Submission</a></li> <li><a href="#_SearchTab" role="tab" data-toggle="tab">Search</a></li> </ul> <!-- Tab Content Containers --> <div class="tab-content"> <div class="tab-pane fade in active" id="_SubmissionTab">@Html.Partial("_SubmissionTab")</div> <div class="tab-pane fade" id="_SearchTab"></div> </div> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<script> $('#tabstrip a').click(function (e) { e.preventDefault() var tabID = $(this).attr("href").substr(1); $(".tab-pane").each(function () { $(this).empty(); }); $.ajax({ url: "/@ViewContext.RouteData.Values["controller"]/" + tabID, cache: false, type: "get", dataType: "html", success: function (result) { $("#" + tabID).html(result); } }); $(this).tab('show') }); </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:
1 2 3 4 5 6 7 8 9 |
public ActionResult _SubmissionTab() { return PartialView(); } public ActionResult _SearchTab() { return PartialView(); } |
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.