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.