Tuesday, October 19, 2010

MVC2 Warning user before navigation on filled form

Scenario:
We deal with so many system on day to day basic and every system has different navigation system. For one of our requirement we had multiple data entry screens.

Now one of the use case was what if user fill the form and click on hyperlink by mistake which will navigate him away from the page and user will use the filled in form data.
1. Client wanted that user should be warned in such case.
2. This should work on New form.
3. This should work on Edit form , that means if user will have prefilled information but should be warned only in the case of changes made.

Solution:
While we thought of multiple solutions, few worked for New but not for edit. Also we wanted kind of generic solution which works on other pages and doesn't depend upon how many textboxes / drop downs/ other controls on the form.

View ( Script ):

 <script language="javascript" type="text/javascript">

var initialdata = $('#frmSample').serialize();

$('#cancelLink').click(function () {
var frmData = $('#frmSample').serialize();
if (WarnIfDirty(frmData)) return false;
});

function WarnIfDirty(frmData) {
if (initialdata != frmData) {
return !confirm("There is unsaved data on this page. Do you wish to continue?");
}
else {
return false;
}
}
</script>
View ( HTML ):


<%= Html.ActionLink("Index", "Index", "NextView", null, new { name = "cancelLink", id = "cancelLink" })%>

0 comments: