为什么这个动作会运行两次?

时间:2017-03-22 20:32:35

标签: c# asp.net-mvc

这是发表评论的动作。出于某种原因,评论被发布两次。当我设置一个断点时,我看到当它触及这个动作的底部时,它会再次回到起点!我无法弄清楚为什么?

[HttpPost]
public ActionResult postComment(string comment, string userId, string workerid)
{
    CleanerManager cm = new CleanerManager("Cleaning_LadyConnectionString");
    CommentsOnUser c = new CommentsOnUser();
    c.Comment = comment;
    c.CleanerId = int.Parse(workerid);
    c.UserId = int.Parse(userId);
    c.Date = DateTime.Today;
    cm.AddCommentOnUser(c);
    return this.RedirectToAction
         ("Profile", new { id = workerid });
}

这是javascript

$(".hiredButton").on('click', function () {
  $("#commentModal").modal();
    $(".postComment").on('click', function () {

        var comment = $("#Message").val();

        var workerId = $(".postComment").data('workerid');
        var userId = $(".postComment").data('userid');


        $.post("/S/postComment", { comment: comment, userId: userId, workerId: workerId }, function () {
            window.location = "http://baltimoresitter.com/S/profile?Id=" + workerId;
        });
    });

});

这是视图

       <button type="button" data-workerid="@Model.Cleaner.id" data-userid="@Model.User.id" class="btn btn-default postComment" data-dismiss="modal">Post Comment</button>

1 个答案:

答案 0 :(得分:1)

每次点击该按钮时,另一个事件都会被注册到&#34; .postComment&#34;,所以该行

$(".postComment").on('click' ...

每次运行都会在click事件上注册另一个函数,你会看到它被多次调用。