Jen143 Jen143 - 3 months ago 57
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 -->

And my JQUERY:

'use strict';

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

var $form = $(this);

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) {
} else {

return false;

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

.on('click', 'a[data-toggle="modal"]', function () { // show modal

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


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 :)


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) {