So I need to do a couple of things when the user leaves the page. I figure I can capture that event with the JQuery window.unload but I'm not sure how to save some data back into the database.
I'd be happy calling another action or something like that but I don't want to stop the user from going to the page they are headed to.
Any ideas?
UPDATED: Solution
Here's the solution I went with (I'll make the error handling a bit nicer later :)).
Since I need to perform a delete operation, I added some extra security after reading this post; http://stephenwalther.com/blog/archive/2009/01/21/asp.net-mvc-tip-46-ndash-donrsquot-use-delete-links-because.aspx
In the view:
$(window).unload(function() {
var ajurl = "/Assignments/unlockAssignment/" + '@model.ID' + "/";
$.ajaxSetup ({
cache: false
});
$.ajax({
type: "DELETE",
url: ajurl,
error: function (xhr, status, error) {
//do something about the error
alert('error');
},
success: function(){
alert('Data Saved:开发者_如何学编程');
}
});
});
The Controller
<AcceptVerbs(HttpVerbs.Delete)>
<Authorize()>
Function unlockAssignment(ByVal id As Integer)
Dim ass As Assignment = db.Assignments.Find(id)
Dim lck = From a In db.AssignmentLocks
Where a.ID = ass.Lock.ID
Select a
db.Entry(lck.FirstOrDefault).State = EntityState.Deleted
db.SaveChanges()
End Function
You could just fire an ajax request on $(window).unload() — I don’t think it would impede the user.
However, I don’t think you’d be able to confirm the results of the ajax call, i.e., handle returned data via a callback. I assume the page would have “moved on” by then. Approach it as a “fire and forget”.
If you need some sort of confirmation that the ajax call was successful, or to handle returned data, look for a way to do it before unload.
精彩评论