I have strange problem with modal widows in ASP.NET MVC. I created a link which is responsible for showing up modal window. The modal window shows up and contains one button – save button. I attached a click eventhandler to this button in order to save the content of the window and then close it. The whole mechanizm looks that way
// this link shows up a modal window
@Html.ActionLink("Add", "Add", "Index", null, new { id = "actionLinkAdd" });
and javaScript
$(function () {
debugger;
$("#actionLinkAdd").on("click", function (event, action) { // attaching to click event
debugger;
event.preventDefault(); //disabling default handler
var $dialog = $('<div></div>');
var $url = $(this).attr('href');
$dialog.empty();
var $kendoWindow = $dialog.kendoWindow({ //window creating
height: "200px",
title: "Dodaj",
visible: false,
width: "200px",
actions: ["Close"],
content: $url // loading of the window's content (partialView)
}).data("kendoWindow");
$kendoWindow.center();
$kendoWindow.open();
function onButtonSaveClick(event) {
debugger;
event.preventDefault();
var $url = $('#target').attr("action");
$.ajax({
url: $url,
type: "POST",
data: $('#target').serialize(),
success: function (response) {
$("#btnSave").unbind("click");
$kendoWindow.close();
$kendoWindow.destroy();
},
error: function (args) {
debugger;
$("#btnSave").unbind("click");
$kendoWindow.content(args.responseText);
}
});
}
$('#btnSave').live("click", onButtonSaveClick); // attaching to click event on save button in the modal window
});
});
Everything works almost great.The problem is that function onButtonClick() is fired couple of times. For example if I open modal window two times this function will be invoked also two times. It’s quite strange for me because I close modal window,destroy it and even unbind all click event attached to btnSave (I also tried to use on and off function but the behavior of the window is the same). What could be reason of this behavior ?
Or even better move the line which binds the event:
down one line thus:
The problem is that you’re calling live every time you create a new dialog but failing to unbind it using ‘unbind’. But you don’t need to, you just bind using live once in the outermost function which is called when the page is ready, and then it will pick up any click on anything with an id = ‘btnSave’. Now you shouldn’t really be creating multiple dialog windows with elements with the same id in them, you should really set the class to ‘btnSave’ but that’s another story..