Wednesday, July 22, 2009

Call ServerSide Method from Javascript

Call ServerSide Method from Javascript

Sometimes we would require to get data from server without postback the page.


For example, we need to validate the Date of Birth field in which the value should not be greater than current date. In this scenario, we need to get the server date and then check the entered value with current date.

For doing this without postback, we can move into PageMethods concept in AJAX.

* Create a Method with System.Web.Services.WebMethod Attribute in your code behind.

[System.Web.Services.WebMethod]
public static string GetDate()
{
return DateTime.Now.ToShortDateString();
}


* Add the following scripts within <body> Tag

<script type = "text/javascript">
function callMethod() {
PageMethods.GetDate(onComplete, onError);
}

function onComplete(result) {
alert('Today : ' + result);
}

function onError(result) {
alert(result);
}
</script>


* Add ScriptManager and make sure the EnablePageMethods should be True.

<asp:ScriptManager ID = "scr" runat = "server" EnablePageMethods = "true"></asp:ScriptManager>


* Call the callMethod from your button click.

<input type = "button" value = "Validate" onclick = "callMethod();" />


Now you can get the server value without postback....

Things we should keep in mind for doing this:

* The server side method should be static method.
* EnablePageMethods should be true in ScriptManager.
* Scripts should be included within <body> tag, not in <head>.


Happy coding...

No comments: