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:

function RedirectToTab() {
        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">
    <li role="presentation" class="@tab1"><a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab">Tab 1</a></li>
    <li role="presentation" class="@tab2"><a href="#tab2" aria-controls="tab2" role="tab" data-toggle="tab">Tab 2</a></li>
    <li role="presentation" class="@tab3"><a href="#tab3" aria-controls="tab3" role="tab" data-toggle="tab">Tab 3</a></li>
</ul>

<div class="tab-content">
    <div role="tabpanel" class="tab-pane @tab1" id="tab1">
         tab 1
    </div>
    <div role="tabpanel" class="tab-pane @tab2" id="tab2">
        tab 2
    </div>
    <div role="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"