Setting Session Variables in ASP.NET from JavaScript

Someone on the ASP.NET forums asked how to set session variables in JavaScript. The answers given ranged from “totally wrong” to “rather misleading” or “marginally helpful”.

So in a nutshell, yes, you can totally do it. Not only will you be able to do it, you will love doing it after you get used to the process of getting it set up.

Here’s the recipe for success:

  • Add an ASP.NET AJAX ScriptManager to your page.
  • Create a simple ASMX Web service using Visual Studio.
  • Uncomment the Attribute directly above the class definition that reads [System.Web.Script.Services.ScriptService] to enable ASP.NET AJAX to see your web methods.
  • Create a method to get or update data in your session, and make sure the Attribute above the web method reads [WebMethod(EnableSession = true)] so you can have access to the session via your web service method.
  • Add a <Services> section to your ScriptManager.
  • In the <Services> section add a <ServiceReference> element with the Path attribute set to the path of your .asmx page.

OK, so that enables the ability to access your session from the client side.

But here’s the really awesome part:  if you include a reference to the web service in your .js file like so:

///<reference path=”~/MyServices/MyService.asmx” />

…you will get IntelliSense in the JavaScript for your web service methods! it’s very cool.

So then you just call your web service methods like you would any other JavaScript function. It’s totally easy and almost magical. It’s one of my favorite features of ASP.NET AJAX.