QHu91_IT
QHu91_IT

Reputation: 319

AJAX loaded PartialView in ASP.NET MVC - script runs more than once

I have some partial views, all of which have some similar classes (.update, .save, .cancel) but their purpose is different. On each page I write a script to work with the classes and use ajax to load the PartialView.

Everything is working except when I click the button to reload the page, the script in this page runs twice, click again and the script runs 3 time.

$('#gridcontainer').load("/webdata/bank", {}, function () {
    alert('Load page'); // alert run 1 time when page load, it normal
    $('body').on('click', '.save', function () { // this function run n time when i load page n time.
          var c = confirm('Do you want save?')
          if (c) {
               $(this).val('Edit').removeClass('save').addClass('update');
               var v = $(this).closest('tr').find('td');
               v.eq(1).find('span').removeClass('hide');
               v.eq(1).find('input').attr('type', 'hidden');
               v.eq(2).find('input.cancel').attr('type', 'hidden');

               var id = $(this).data('id');
               // more code
          }
     });
}

Upvotes: 1

Views: 458

Answers (1)

cwishva
cwishva

Reputation: 1978

You should Remove any previous attached events when reloading , Use Jquery OFF

$('#gridcontainer').load("/webdata/bank", {}, function () {
    alert('Load page'); // alert run 1 time when page load, it normal
    $('body').off( "click", ".save").on('click', '.save', function () { // this function run n time when i load page n time.
          var c = confirm('Do you want save?')
          if (c) {
               $(this).val('Edit').removeClass('save').addClass('update');
               var v = $(this).closest('tr').find('td');
               v.eq(1).find('span').removeClass('hide');
               v.eq(1).find('input').attr('type', 'hidden');
               v.eq(2).find('input.cancel').attr('type', 'hidden');

               var id = $(this).data('id');
               // more code
          }
     });
}

Upvotes: 2

Related Questions