N. Sch
N. Sch

Reputation: 687

Why is this action running twice?

This is an action to post a comment. For some reason the comment is being posted twice. When I put a breakpoint, I see when it gets to the bottom of this action, it goes back to the beginning again! I can't figure out why?

[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 });
}

Here is the 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;
        });
    });

});

Here is the view

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

Upvotes: 0

Views: 97

Answers (1)

Haddar Macdasi
Haddar Macdasi

Reputation: 3555

Each time you click the button another event is being registered onto the ".postComment", so the line

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

every time runs is registering another function on to the click event and you will see it called more than once.

Upvotes: 1

Related Questions