Friday, September 28, 2012

Mixing Client Side with Server side ASP.Net

Hi readers

Have you ever had the need to call a server side method from client side or a client side method from server side?

Well i've had this need so many times, so i've searched so many sites and read so many blogs about this. So i also wanted to write a post about this.

 First we'll see how to call a client side method from server side. Its pretty simple. you just have to register the method to the client side.

ClientScript.RegisterStartupScript(typeof(Page), "click", "alert('Hi');",true); ClientScript.RegisterStartupScript(typeof(Page), "click", "initialize()",true);

The first one will show an alert with text Hi and the second one will call the method initialize which is declared in the page.

Well lets see the calling of server side methods from client For this we'll need a script manager and the script manager's 'EnablePageMethods' attribute must be 'true'. And in the codebehind file you'll need to have a public static method

[System.Web.Services.WebMethod]
public static string sayHello(string name)
{
    return "Hello "+name;
}

And this method can be called from javascript
 
function sayHello(name) {
	PageMethods.sayHello(id, sayHellotSuccess, sayHellotFailure);
}
function sayHelloSuccess(result, userContext, methodName) {
	alert(result);
}
function sayHellotFailure(error, userContext, methodName) {
	alert(error.get_message());
}      

Now calling the method sayHello(name) will alert the output from server. And if you throw an exception in the server the 'sayHellotFailure' method will be executed.

 Leave a Comment if you like this post