Getting active tab on button click and pass it to controller

By : equisde
Source: Stackoverflow.com
Question!

I'm currently working with MVC3 and Bootstrap.

I have a view with several Bootstrap tabs. Also I have a button [Create] that calls to Create() function in controller.

When clicking on [Create] button I need the following:

1.- Get the active tab id in order to pass it to the controller.

2.- Remain on the current (active) tab when the user has posted data and the page reloads

I know that i need to use Javascript to get the active tab and AJAX to pass the ID to the controller. I tried to mix them unsuccessfully in different ways. Actually I'm newbie in AJAX but i noticed that I'm missing to call the actions on button click event, but i donĀ“t know how to codify it :(

My JS:

$(function() { 
    var activeTab = null;
    $('a[data-toggle="tab"]').on('shown', function (e) {
      activeTab = e.target;
      //save the latest tab
      localStorage.setItem('lastTab', $(e.target).attr('id'));

      $.ajax({
                url: '@Url.Action("Create")',
                type: 'GET',
                data: postData,
                success: function(result) {

                }
            });

    });

      //go to the latest tab, if it exists:
      var lastTab = localStorage.getItem('lastTab');
      if (lastTab) {
        $('#'+lastTab).tab('show');
      }
});

[Create] button...

<button type="submit" class = "btn btn-success">
    <i class="icon-plus icon-white"></i> Create
</button>

Any help will be highly appreciated.

Thanks in advance!

By : equisde


Answers

There are many ways you can do this, it just depends on what technologies/frameworks you want to use. If you want to stick with vanilla MVC, you can look at the AjaxHelpers. These offer markup helpers like @Ajax.BeginForm(...) and @Ajax.ActionLink(...) which automagically submit form data or invoke a controller action from a link via an AJAX call.

If you want more control over how AJAX calls are made, you can look at client side frameworks like Backbone.js or Knockout.js. I actually prefer Knockout as it allows you to easily adopt the MVVM design pattern in MVC. For example, here's a simple Knockout view model:

var ViewModel = function () {
    var self = this;

    self.tabs = ko.observableArray([
        { id: 1, name: 'Tab 1' },
        { id: 2, name: 'Tab 2' },
        { id: 3, name: 'Tab 3' }
    ]);

    self.saveChanges = function () {

        // Here's where you can get the id of the selected tab
        // and make your ajax call

        var tab = $('.tab-content 


This video can help you solving your question :)
By: admin