Call WebMethod from Javascript in ASP.NET

6. November 2009 17:24

I needed to be able to remove a session variable from javascript so this post will talk about how to call a webmethod from javascript to remove a session item.  I will be utilizing a JS file, ASP.NET page with a WebMethod exposed in it and an asp.net user control.

The basis of this is a few things:

First we need an <asp:ScriptManager> on the ASPX page with the EnablePageMethods property set to true:

Second we need to expose a static function in our ASPX code behind so it can be available to our javascript file.

Note the [WebMethod] above the function and that the function is static. This is what allows us to make it available to the javascript file.  

Please make sure to add the statement using System.Web.Services; into the ASPX page, otherwise [WebMethod] will throw an error when compiling.

Third we need a ScriptProxyManager on the ASCX control with a reference to your JS file. This will also take care of including the JS file for your control as well so there is no need to add the <script src=....> tag. Put this as the first thing in your ASCX control.

Fourth we need the code from the JS file to bring it all together:

--------------------------------------------------------------

Anywhere in your javascript you can call the ClearSessionItem() method. Such as

function MyFunction(item){
    
    ClearSessionItem("MySessionItem");
}

Also you could call it via an onclick event with an HTML element such as:

<span onclick="ClearSessionItem('MySessionItem')">Clear Item</span>

---------------------------------------------------------------
Of course you can use this concept for almost about anything.  It allows you to not have a seperate ASMX file (Web Service) in your project.  Again, the concept here allows you to call a server side method inside javascript.


Resources:

http://www.asp.net/ajax/documentation/live/Tutorials/ExposingWebServicesToAJAXTutorial.aspx
http://www.asp.net/ajax/documentation/live/ViewSample.aspx?sref=Sys.Net.PageMethod%23PageMethod.aspx
http://www.asp.net/AJAX/Documentation/Live/ViewSample.aspx?sref=Sys.Net.PageMethod/cs/PageMethod.js


Good luck...leave questions if you got them and I'll do my best to answer  

Tags: ,

ASP.NET | Javascript

blog comments powered by Disqus



My Random Thought

I think the OCW is a great thing to have available to those who are in school, just finished school or just want to educate themself

http://ocwconsortium.org/

John On Twitter

Discounts