I have a scenario of buttons invoking Url.Action
to different views. Upon loading the view, I want to set appropriate button (acting as tabs) to be selected. Setting the value in ViewBag
and trying to retrieve it yields empty string.
The Layout page sets the value of selected button through AJAX call subsequent to which it is reloaded as
$(function () {
var tab = "My Lists";
$('#btnMyLists').click(function () {
$.ajax({
type: "POST",
url: '@Url.Action("SetSelectedTab", "Home")',
datatype: "json",
data: { "tab": tab },
success: function (response) {
window.location.href = '@Url.Action("MyLists", "AssocLists")';
},
error: function (errordata) {
}
});
});
});
I added a method to store the state of the selected tab in the ViewBag in Home Controller as
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SetSelectedTab(string tab)
{
ViewBag.SelectedTab = tab;
return new JsonResult { Data = new { Ok = true, message = string.Empty } };
}
but seems like the retrieval of ViewBag variable seems to be happening prior to rendering of the view, which utilizes the Layout or I am unsure how to obtain the ViewBag variable to successfully set the selected class of the button.
$(function () {
//DOES NOT WORK - EMPTY STRING
var seltab = "@(ViewBag.SelectedTab)";
if (seltab.length > 0 && seltab == "My Lists")
$(btnMyLists).addClass('homepageHeaderButtonActive').siblings().removeClass('homepageHeaderButtonActive');
})