-1

I have a page with a variable number of textareas. When the unload event is triggered, I check which textareas have been changed, then perform an AJAX post to an MVC controller, which adds/updates the entities in the database.

Everything seems to work, except when I refresh the page. The database operations take longer than it takes to serve the page, requiring you to refresh twice before you see the changes.

JavaScript:

$textarea.one("change", function () {
    // Changed textareas get 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 to avoid using $.ajax option async: false, since it has been deprecated.

Jamie Lester
  • 848
  • 9
  • 20

2 Answers2

1

Keep in mind this will block the UI while any synchronous code is running during the unload event. You can add a synchronous loop after you fire off the async request, checking for some value that gets set in the callback for the async request. Example here: Call An Asynchronous Javascript Function Synchronously

Another option is to track that you have unsaved changes on the form, and use the onbeforeunload event to prompt the user to save their changes before leaving the page, effectively cancelling the page unload and allowing the user to click "save". AJAX call on onbeforeunload to save data

Community
  • 1
  • 1
BateTech
  • 5,780
  • 3
  • 20
  • 31
0

Place the body of both methods in a lock statement so that when you hit refresh you will not receive any data until database updates are performed.

This is a bad idea, but it will probably work.

Bogdan
  • 484
  • 2
  • 7