In this article I will explain with an example, how to use ClientScript and ScriptManager RegisterClientScriptBlock and RegisterStartupScript functions in Static WebMethod in ASP.Net using C# and VB.Net.
It is not possible to use ClientScript and ScriptManager RegisterClientScriptBlock and RegisterStartupScript functions in Static WebMethod and hence the solution is to call the JavaScript function inside the success method of the AJAX call.
ASP.Net WebMethod
The following WebMethod, simply returns true when the request is received.
C#
[System.Web.Services.WebMethod]
public static bool GetResponse()
{
return true;
}
VB.Net
<System.Web.Services.WebMethod()> _
Public Shared Function GetResponse() As Boolean
Return True
End Function
Calling JavaScript function after the AJAX call is completed
The following HTML Markup consists of an HTML Button assigned with a jQuery OnClick event handler. When the Button is clicked, jQuery AJAX call to the ASP.Net WebMethod is made and once the response is received in the Success event handler, the page is redirected to another page.
<input id="btnGetResponse" type="button" value="Redirect" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGetResponse").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetResponse",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d == true) {
alert("You will now be redirected.");
window.location = "//www.aspsnippets.com/";
}
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads