Thursday, April 25, 2013

Using jQuery to call a fire and forget C# WebMethod

Recently I ran across a need to log some information about a user performing a certain action but I did not want to wait for a success or failure response from the server. I just wanted to fire off the request and forget about it. I will outline some basics on how you can achieve this. The code provided is using jQuery, C# and .NET. First lets write the code for the logging on our server side.

Now for the above to work there are a few conditions that must be met.

  1. We have to decorate the function with a [WebMethod(true)] attribute.
  2. We have to make it a static function.
  3. This function MUST be written within a .aspx file. (cannot be in a .ascx control or a master page and it cannot be within a standalone class.)
  4. Here I have added the code to my Default.aspx page code behind.
As for what this function does, well that's quite simple. We are creating a UsersActionLog.DateTime.txt file if none exists and appending to the file if it does. The file has the users session id, browser name and version along with what time this call was made. Now since we don't want to take too many cycles or cause exceptions we wrap it all up in a try catch block but ignore any exceptions that occur. You can of course change this behavior to suit your needs.

Now that we have the code behind we need a way to trigger it. So lets write some jQuery that will call into this method and then forget about the response.

In jquery we will create the path to where the web method resides. This is the full path with protocol host and page path all included. If you notice we are doing a short form if statement that allows his script to work even if we are debugging the application locally (So you will need to replace AppName with the name of your website). The script fires each time the users clicks on an html element with id="someElem".

And that's all it takes!

No comments:

Post a Comment