jquery - ASP.NET MVC3 set class for button in Layout.cshtml upon reload -
i have scenario of buttons invoking url.action
different views. upon loading view, want set appropriate button (acting tabs) selected. setting value in viewbag
, trying retrieve yields empty string.
the layout page sets value of selected button through ajax call subsequent reloaded
$(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 method store state of selected tab in 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 retrieval of viewbag variable seems happening prior rendering of view, utilizes layout or unsure how obtain viewbag variable set selected class of button.
$(function () { //does not work - empty string var seltab = "@(viewbag.selectedtab)"; if (seltab.length > 0 && seltab == "my lists") $(btnmylists).addclass('homepageheaderbuttonactive').siblings().removeclass('homepageheaderbuttonactive'); })
a viewbag
's lifetime 1 request. when setselectedtab
action gets called set viewbag.selectedtab
, action finishes , json result sent client viewbag
destroyed. on next request viewbag
empty.
what should make hidden field (<input name="selectedtab" type="hidden"...
)in view, , when selected tab changes should set value in hidden field (on client side, in js). when form submitted server read value there , not viewbag. option use session instead of viewbag, don't recommend such simple scenario.
for more information on can check out following question: what right time viewdata, viewbag, session, tempdata.
Comments
Post a Comment