Monday, October 22, 2012

Call PageMethod From JavaScript in ASP.NET Ajax


Most of time we need to call page method(server side code) by client side script(JavaScript) without post back. I will accomplish this using the Page Methods feature. To do this we are using ASP.Net Ajax. Using page method a JavaScript knowledge will help.

Create a script manager control on your form, to use PageMethods,we will need to set the EnablePageMethods property to true of ScriptManager.
Enable Page Methods on your ScriptManager
<asp:ScriptManager ID="ScriptManager1" runat="server"  EnablePageMethods="True"> 
      </asp:ScriptManager>

Create static method and set WebMethod attribute
Now we create a static method on our code behind file. It must marked with the WebMethod attribute, if we are not using WebMethod attribute we can't able to call this page method via javascript.To use WebMethod attribute we need to add System.Web.Services namespace.
using System.Web.Services;
[WebMethod]
public static bool WelcomeMessage(string name)
{
    if (name == "ASP" || name == "C#" || name == "Ajax" || name ==     "JQuery")
        return true;
    else
        return false;
}
Call from JavaScript
Call this method from JavaScript as follows:
<script type="text/javascript">
var divWelcomeMessage =document.getElementById('divWelcomeMessage'); function CallMethod(username) {     //initiate the Ajax page method call     //alert(username);     PageMethods.WelcomeMessage(username,OnSucceeded);     } // Callback function invoked on successful completion of the page method. function OnSucceeded(result, userContext, methodName) {     if (methodName == "WelcomeMessage")     {         if(result==true)             divWelcomeMessage.innerHTML = "Welcome Dear";         else             divWelcomeMessage.innerHTML = "Go from here";     } }
</script>
We call this JavaScript on the textbox keyup event as follows.

<input type="text" id="txtusername" runat="server"onkeyup="CallMethod(this.value);"/
><div id="divWelcomeMessage" /gt;

No comments:

Post a Comment