Jen143 Jen143 - 1 month ago 20
Javascript Question

JQuery called the Method in the Controller(MVC) twice

I'll have this code in the index.cshtml

<a href='@Url.Action("Create", "ShippingMethods")' data-toggle="modal" data-target=".modal" data-wrap="modal-lg"><i class="fa fa-edit fa-fw"></i> Edit</a>

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="Modal">
<div class="modal-dialog">
<div class="modal-content">
<!--Content Inside Here-->
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>


And my JQUERY:

'use strict';

(function ($) {
/* Ajax Form Submit for Modal */
var ajaxFormSubmit = function () {

var $form = $(this);

$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
beforeSend: function () {
$('.spinner').addClass('fa fa-spinner fa-pulse fa-2x fa-fw');
}
})
.done(function (data) {
var $target = $($form.attr('data-target'));

if (data.status == true) {
$('.modal').modal('hide');
location.reload();
} else {
$target.replaceWith(data);
}
});

return false;
}

/* Empty Modal Content on Hide */
$('.modal').on('hide.bs.modal', function (e) {
$('.modal-content').empty();
$('.modal-dialog').removeClass('modal-lg modal-sm');
});

$('.ShippingMethods')
.on('click', 'a[data-toggle="modal"]', function () { // show modal
$('.modal-dialog').addClass($(this).attr('data-wrap'));
$('.modal-content').load($(this).attr('href'));
})

.on('submit', '.ajaxForm', ajaxFormSubmit); // modal ajax form submit

})(jQuery);


I was wondering why the method in the controller called twice. When in fact I only clicked it once. This function was called twice everytime I clicked the button.

public ActionResult Create()
{
var whs = new PluginManager().GetAllData();
ViewBag.PluginId = new SelectList(whs, "PluginId", "Description");
return View();
}


Anyone have idea why it is acting strange? I can't figure out what's the problem in here? Thanks in advance for the help and advice :)

Answer

You are not preventing the default behaviour of the link. You have an onclick listener, that makes a call using jQuery's load, but after the click listener has been executed, the link will proceed to its default behaviour, which is to follow the link in the href, and that's your second call.

Accept the event as a parameter to your listener, and call preventDefault on that to stop your browser from following the link.

.on('click', 'a[data-toggle="modal"]', function (e) {
        e.preventDefault();
        $('.modal-dialog').addClass($(this).attr('data-wrap'));
        $('.modal-content').load($(this).attr('href'));
    })
Comments