Skip to content Skip to sidebar Skip to footer

How To Invoke Javascript Method Based On A Value Of Viewbag

I'm working on small mvc application, and on my view there is tab control which has 3 tabs, and depending on ViewBag value I need to open my third tab, here is image of a how my vi

Solution 1:

Just use the razor engine to output your ViewBag value in the javascript:

functionRedirectToTab() {
        var customVal = '@ViewBag.SuccessBody';
        if (customVal == 'True') {
            $('#myTab a[href="#tab_content3"]').tab('show');
        }
}

Now you can call this from the doc ready:

$(document).ready(function () {
    RedirectToTab();
});

Solution 2:

You don't need to use JavaScript to open the tab. You can do it your Razor view which has the benefit of not seeing the active tab switch from 1 to 3 when the page loads. Here is a simple example with 3 tabs:

@{ 
    string tab1 = null, tab2 = null, tab3 = null;
    if (ViewBag.SuccessBody == null)
    {
        tab1 = "active";
    }
    else
    {
        tab3 = "active";
    }
}
<ul class="nav nav-tabs" role="tablist">
    <lirole="presentation"class="@tab1"><ahref="#tab1"aria-controls="tab1"role="tab"data-toggle="tab">Tab 1</a></li><lirole="presentation"class="@tab2"><ahref="#tab2"aria-controls="tab2"role="tab"data-toggle="tab">Tab 2</a></li><lirole="presentation"class="@tab3"><ahref="#tab3"aria-controls="tab3"role="tab"data-toggle="tab">Tab 3</a></li>
</ul>

<divclass="tab-content"><divrole="tabpanel"class="tab-pane @tab1"id="tab1">
         tab 1
    </div><divrole="tabpanel"class="tab-pane @tab2"id="tab2">
        tab 2
    </div><divrole="tabpanel"class="tab-pane @tab3"id="tab3">
        tab 3
    </div></div>

Post a Comment for "How To Invoke Javascript Method Based On A Value Of Viewbag"