3

I am using Visual Studio 2010 and MVC 3 with AJAX/JQuery. The issue I am having is that the code is posting something twice. It only happens when you post something, then do it again.

Here is my JS:

$(document).ready(function () {
   BindEvents();
});

function BindEvents() {
$('#OpenCommentDialog').click(function (event, ui) {
    var id = $(this).attr('data');
    $('#NewCommentDialog').dialog({
        open: function (event, ui) {
            $('#BugID').val(id);
            var form = $('form', '#NewCommentDialog');
            form.submit(function (e) {
                var comment = form.serialize(true);
                CreateComment(comment);
                return false;
            });
        }
    });
    $('#NewCommentDialog').dialog('open');
    return false;
});
}

function CreateComment(comment) {
if (comment != null) {
    $.post('/Comments/Create/', comment, function (data) {
        if (data == 'Success') {
            var id = $.parseQuery(comment);
            GetComments(id.BugID);
            $('#NewCommentDialog').dialog('close');
        }
    });
}
}

function GetComments(id) {
$('#Comments').find('tr').remove();
$.getJSON('/Comments/GetComments', { id: id }, function (data) {
    if (data != null) {
        if (data.length > 0) {
            $('#CommentListTemplate').tmpl(data).appendTo('#Comments');
        }
    }
});
}

My HTML page has a JQuery dialog box that calls a CreateCommentPartial.cshtml file. When the user fills it out, it calls the "CreateComment" function, which then calls the "GetComments" and refreshes the comments after the new one is posted.

Now, here's the issue. If you click the "Create Comment" link again, without reloading the page and fill out the form, the "CreateComment" is fired twice and "GetComments" is fired twice as well. Firebug shows me this as well.

What am I doing wrong here? If you reload the page (F5) after posting it doesn't do this. But it defeats the purpose. One should be able to submit a comment multiple times without reloading the page.

4

2 回答 2

1

您在哪里声明了上述脚本?我在通过部分视图添加到页面的脚本中遇到了类似的问题。不知何故,每次单击按钮都会将脚本添加到页面中,从而使脚本和帖子数量相乘(脚本的每个副本触发一次)。我通过将脚本放在单独的 .js 文件中并在母版页中引用它来解决问题

于 2011-02-26T09:05:53.050 回答
0

问题是方法被调用两次引起的,可以解决,用switch变量什么时候关联事件来控制。

例子:

 var $isActualizaComentarioEventoAsignado = false;

 if (!$isActualizaComentarioEventoAsignado) {
                $isActualizaComentarioEventoAsignado = true;
                $('#pepe').bind('clic', function(e) {});
}
于 2014-07-22T14:57:10.717 回答