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:
- 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;
}
- 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;
}
- Uncomment the line to allow webservice to be accessed from JavaScript:
[System.Web.Script.Services.ScriptService]
- 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>
- 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>
- 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>
- Add normal aspx page that uses master page and run the solution.