user4432964
user4432964

Reputation:

dynamically load content when tab is active in mvc bootstrap tab-content

I am using bootstrap and ASP.NET mvc to create a web app. I am using partial views on each tab however right now all the data is coming in at the same time. I would like to call my partial to query and return data only when the tab is active. How can I do that?

<div>
    <ul class="nav nav-tabs nav-justified">
        <li class="active"><a href="#tab1" data-toggle="tab">Service</a></li>
        <li><a href="#tab2" data-toggle="tab">Instrument</a></li>
    </ul>

    <div class="tab-content">

        <div class="tab-pane fade in active" id="tab1">
            @Html.Action("Index", "Controller1")

        </div>
        <div class="tab-pane fade" id="tab2">
            @Html.Action("Index", "Controller2")
        </div>

    </div>
</div>

Upvotes: 1

Views: 4933

Answers (3)

KevDevMan
KevDevMan

Reputation: 818

You would need to put a onClick event on your tabs, somthing like below should work for you

<ul class="nav nav-tabs nav-justified">
   <li class="active" data-ref="1"><a href="#tab1" data-toggle="tab">Service</a></li>
   <li data-ref="2"><a href="#tab2" data-toggle="tab">Instrument</a></li>
</ul>


<div class="tab-content">
    <div class="tab-pane fade in active" id="tab1">
        <div id="tabone"></div>
    </div>

$(".nav-tabs li").click(function(){
  var pageId = $(this).data('ref');
   $.ajax({
      url: url,
      data: {pageId:pageId },
      success: function(response){
        if(pageId == 1)
        {
           $('#tab1').replaceWith(response);
        }
        else.... 
      }
    });
});

Upvotes: 2

DominicValenciana
DominicValenciana

Reputation: 1731

Javascript Magic

ASP.net doesn't inherently come with that feature available. The method I would use would be to setup a url in your controller returning a partial viewand then have make an ajax request to that url to load it's content in to your web page. The method I described can be seen as an example Here

tdlr;

Make a partial view in your controller, and load it using ajax.

Upvotes: 0

Jigarb1992
Jigarb1992

Reputation: 848

Try this Code

<div>
    <ul class="nav nav-tabs nav-justified">
        <li class="active"><a href="#tab1" id="openTab1" data-toggle="tab">Service</a></li>
        <li><a href="#tab2" id="openTab2" data-toggle="tab">Instrument</a></li>
    </ul>

    <div class="tab-content">

        <div class="tab-pane fade in active" id="tab1">
            @Html.Action("Index", "Controller1")

        </div>
        <div class="tab-pane fade" id="tab2">
            @Html.Action("Index", "Controller2")
        </div>

    </div>
</div>

<script>
    $("#openTab1").on("click", function() {
        $("#tab1").load('/Controller1/Index');
    });

    $("#openTab2").on("click", function() {
        $("#tab2").load('/Controller2/Index');
    });
</script>

Upvotes: 0

Related Questions