c# - Automatically saving form data on page unload not completing before page refresh -
i have page variable number of textareas. when unload event triggered, check textareas have been changed, perform ajax post mvc controller, adds/updates entities in database.
everything seems work, except when refresh page. database operations take longer takes serve page, requiring refresh twice before see changes.
javascript:
$textarea.one("change", function () { // changed textareas stored in 'unsaved' here... }); $(window).on("unload", function () { if (unsaved.length > 0) { var assignmentdetails = []; // post data formationg goes here... $.ajax({ type: 'post', url: '/home/upload', data: json.stringify(assignmentdetails), contenttype: 'application/json; charset=utf-8', }); } });
controller:
public class homecontroller : controller { public actionresult index() { using (var context = new sandboxcontext()) { viewbag.assignments = context.assignments.include(a => a.details).tolist(); } return view(); } [httppost] public emptyresult upload(list<assignmentdetailviewmodel> models) { if (models.count > 0) { using (var context = new sandboxcontext()) { foreach (var model in models) { // database insertion logic goes here... } context.savechanges(); } } return new emptyresult(); } }
i want avoid using $.ajax option async: false, since has been deprecated.
keep in mind block ui while synchronous code running during unload event. can add synchronous loop after fire off async request, checking value gets set in callback async request. example here: call asynchronous javascript function synchronously
another option track have unsaved changes on form, , use onbeforeunload event prompt user save changes before leaving page, cancelling page unload , allowing user click "save". ajax call on onbeforeunload save data
Comments
Post a Comment