Select Tab On Page Load In Asp.net Mvc
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 f
Solution 1:
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')
})
Solution 2:
First of all, you should change the argument type from object to string. If you keep that as object , When you read it in your razor view from ViewBag, you are not going to get the string you expected (A or B), instead you are going to get System.Object
public ActionResult Index(string id = null)
{
if (id != null)
ViewBag.ActiveTab = id.ToString();
return View();
}
Also, You should enable a tab by calling the tab method on the anchor tag for that tab. I changed your markup to include an Id for each anchor tag so that we can select the element in our jQuery code later.
<ulclass="nav nav-tabs"><liclass="active"><adata-toggle="tab"id="link-tabA"href="#productA"><spanclass="glyphicon glyphicon glyphicon-plus-sign"></span>productA
</a></li><li><adata-toggle="tab"id="link-tabB"href="#productB"><spanclass="glyphicon glyphicon glyphicon-align-left"></span>productB
</a></li></ul>
Now in your document ready, use the value of @activeTab
variable value (Which you read from your ViewBag already) to build the jQuery selector expression of the a tag and call the show method on that.
$(function () {
var selector = '@activeTab';
if(selector)
{
$("#link-tab"+selector).tab('show');
}
});
Post a Comment for "Select Tab On Page Load In Asp.net Mvc"