Tag-Archive for ◊ ScriptMethod ◊

Author:
Wednesday, February 24th, 2010

Well.. every day I’m amazed by the vast differences in the programming methodologies of enterprise server programming or windows programming with web development. For a guy like me who spent most of my career working on BizTalk or Win forms development, ASP.net programming is a kind of adventure.

Anyways, my recent adventures, modifying session variables using JavaScript.  Well apparently, there is no straight forward way to do this. In fact, there is no way you can do this if you don’t use AJAX extensions.  And yes, you are right as the reason is, these session variables are maintained at server.

There is this concept called €œPageMethods€.  This is one of the options we can use to invoke server side code from JavaScript without a post back.  

What are PageMethods?

The PageMethods enables the using of server side code (note: this code should be code behind of a page) on the client side. The PageMethods can only be added to the page itself so it can’t be used to invoke methods in class libraries or code with in a user control.

How to Use PageMethods?

To make server side code as a PageMethod, we need to decorate the page with the ScriptMethod and / or WebMethod attributes. Also, these methods need to be static.  

PageMethods Example

Lets look at a simple example of how to use PageMethods.
In the page I have put the following method which returns a €œHello€ string: 

[ScriptMethod, WebMethod]   public static string GetTextForLabel()   {      return “Hello”;

   }

 

On the client side I have the following scripts which run that method:

<script type=”text/javascript”>      function InsertLabelText() {          PageMethods.GetTextForLabel(onSuccess, onFailure);      } 

      function onSuccess(result) {

          var lbl = document.getElementById(‘lbl’);

          lbl.innerHTML = result;

      } 

      function onFailure(error) {

          alert(error);

      }

      InsertLabelText();

    </script>

 If you are using any 3rd party component suits such as Telerik or DevExpress, there is a high chance of them providing a simplified wrapper to PageMethods.  For example, €œAjaxManager€ of Telerik can be used to invoke service side code using JavaScript without a post back.