Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Access Server Side (webservice) from JavaScript in Master Page

0.00/5 (No votes)
5 Nov 2013 1  
This tip describes the steps to access server side (webservice) from JavaScript in master page.

Introduction

This tip describes the steps to access server side (webservice) from JavaScript in master page.

Using the Code

This code can be helpful for situations when you need to access server side from master page avoiding full page postback.

You need to follow the steps given below:

  1. Add webservice (asmx file) that contains the server side function you want to access from JavaScript:
    [WebMethod]    
    public void AtServerSide(int a , string b)    
    {         
     int i = 0;    
    }  
  2. To access the Session variable in the webservice, you need to add the attribute EnableSession = true:
    [WebMethod(EnableSession = true)]
    public void AtServerSide(int a , string b)    
    {         
     Session["CountCalledFromJS"] = Convert.ToInt32(Session["CountCalledFromJS"]) + 1;  
    }  
  3. Uncomment the line to allow webservice to be accessed from JavaScript:
    [System.Web.Script.Services.ScriptService]    
  4. Add master page and add reference to your webservice created above (add code in masterpage.master after form tag):
    <asp:ScriptManager ID="ScriptManager1" 
    runat="server" EnablePageMethods="true">
        <Services>
            <asp:ServiceReference Path="../webservice.asmx" />
        </Services>
    </asp:ScriptManager> 
  5. Add HTML markup to master page to call to server:
     <h1>Ajax Call from master page to asmx through javascript</h1>
    <label title="Click to access server from javascript" 
    onclick="AccessServerSide();">Click to access server from javascript</label> 
  6. Add JavaScript in masterpage / separate file to call the webservice as normal function call. Here my webservice class name is "Webservice". You need to replace the text with your webservice class name.
    <script type="text/javascript">
        function AccessServerSide() {
            WebService.AtServerSide(1, 'Hello');
        }
    </script> 
  7. Add normal aspx page that uses master page and run the solution.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here