ASP.NET Client-Side Dirty-Form Handling
I've been trying to find the best way to handle this, this being alerting the user of an ASP.NET web form to the impending loss of data due to either:
-Changing forms via a link click, -Hitting "Back", -Closing the browser
I want a simple dialog to appear when they do so, giving them the option to change their minds. If they do, then the form remains. If they don't, carry on.
I've tried several jQuery plugins to handle this and am currently on dirty_form. It is properly trapping dir开发者_运维问答ty forms and alerting me when I click a link or try to close the window (it doesn't handle back).
Unfortunately, handling the dirty form situation isn't enough as I cant seem to make it DO anything. My code:
<script type="text/javascript">
$(document).ready(function () {
$("#form2").dirty_form().dirty(function (event, data) {
/*what here */
});
});
</script>
How do I set this so that if they choose to go forward, it does and if they don't, it doesn't?
Also, how to I trap the browser "Back" function and handle it in the same way?
Following the answer at this question here on SO, I implemented this dirty_form plugin successfully in our app. This is what we ended up doing:
// A global variable to table any existing onbeforeunload event
var oldOnBeforeUnloadEvent;
// onDirty event that gets triggered by the plugin.. add visual cue to the user to show dirtiness
function onDirty(event, data) {
$("#form2 div.dirtyIndicator").addClass("redAsteriskBG");
}
// onClean event that gets triggered by the plugin.. remove the dirty indicator
function onClean(event, data) {
$("#form2 div.dirtyIndicator").removeClass("redAsteriskBG");
}
// Check for presence of any inputs that are changed
function checkForDirtyElements() {
var message = '';
var dirtyElements = $('.myChangedClassName').length;
if (dirtyElements > 0) {
message += "IF YOU CONTINUE, ALL YOUR CHANGES WOULD BE LOST!";
}
return message;
}
// Our onbeforeunload event that does all the magic
function myOnBeforeUnload() {
var message = checkForDirtyElements();
if (message === '') {
if (oldOnBeforeUnloadEvent !== null) {
message = oldOnBeforeUnloadEvent();
}
}
if (message.length > 0) {
return message;
}
}
$(document).ready(function () {
// On page load set-up/initialize the dirty form with onDirty and onClean events
$("#form2").dirty_form({
changedClass: 'myChangedClassName'
}).dirty(onDirty).clean(onClean);
// Save the existing onbeforeunload event to a global variable and attach our custom onbeforeunload
oldOnBeforeUnloadEvent = window.onbeforeunload;
window.onbeforeunload = myOnBeforeUnload;
});
精彩评论