posted 4/14/2009 by Vijendra Shakya
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 attributeNow 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 JavaScriptCall 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.
<div> <input type="text" id="txtusername" runat="server"onkeyup="CallMethod(this.value);"/> <div id="divWelcomeMessage" ></div> </div>
Hi,
My query is simple:-
How we can call Normal Non-Static method from client side?
I mean suppose we have create a methos name like add() then how we can call this method.
This comment is awaiting moderation.
Really a wonderfull and simple article, however I would like to add that sometimes [WebMethod] does not work properly and we need to add [ScriptMethod] tag also.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18