4

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Fire and forget sounds fine. I'm trying to implement a locking feature so other users can't edit the record if another user has it open. I haven't really used Ajax before; Can someone provide a simple example?
@Tom: check out the pluralsight videos here: asp.net/mvc (they are free and very good starting point).
I've done this although with PHP. Not much difference -- the key was using $(window).unload() and indeed assuming nothing behind the request being made. It seemed to work fine.
@Tom Here is the basic jQuery ajax call, and here are some methods that make it a little simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.