Introduction
This tip describes the steps to access server side web service (asmx) from master page JavaScript. This can be helpful in situations when you want to prevent full page postback and need to communicate from client side to server side from master page.
Using the Code
You need to follow the steps given below:
- Add webservice (asmx file) that contains the server side function you want to access from jquery:
[WebMethod]
public string HelloWorld(int Variable1, string Variable2)
{
return "Hello World";
}
- Uncomment the line to allow access to webservice from JavaScript:
[System.Web.Script.Services.ScriptService]
- Add master page and add the markup after the
form
tag:
<span id="ArticleContent">
<h1>Access server side from jquery ajax from master page</h1>
<label title="Click to access server from javascript"
onclick="SetTabSessionValue(12, 'Hello');">
Click to access server from javascript</label>
</span>
- Add the JavaScript function that is called when you click on the label to master page. Adjust your webservice path and name accordingly (my webservice name is WSAccessMPJquery.asmx). Also adjust the path for jquery min.js.
<script src="js/jquery-1.8.3.min.js"
type="text/javascript"></script>
<script>
function SetTabSessionValue(Variable1, Variable2) {
var param = "{'Variable1':" + JSON.stringify(Variable1) +
",'Variable2':" + JSON.stringify(Variable2) + "}";
$.ajax({
type: "POST",
url: "WSAccessMPJquery.asmx/HelloWorld",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: SetTabSessionValueSucceed,
error: SetTabSessionValueFailed
});
}
function SetTabSessionValueSucceed(result) {
alert("text from server: "+ result.d);
}
function SetTabSessionValueFailed() {
alert('call failed');
}
</script>
- Add normal aspx page that uses master page and run the solution.