Home > ASP.Net, Javascript > Call Page Method Using Javascript

Call Page Method Using Javascript


Hi all,

Try this example to Call Page Method Using Client Side -Javascript in ASP.Net

ASP.Net AJAX ScriptManager allows you to call Server Side ASP.net methods from client side without any PostBack using PageMethods. Actually it is an AJAX call to the server but it allows us to call the method or function defined server side.

Enabling PageMethods
The first thing you need to do is add a ASP.Net AJAX ScriptManager to the page and set itsEnablePageMethods property to true as shown below

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

HTML Markup :-

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server" ></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()"/>
</div>
</form>

Client Side Method :-

<script type="text/javascript">
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>

Server Side Methods :-

[System.Web.Services.WebMethod]
publicstaticstring GetCurrentTime(string name)
{
return"Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net, Javascript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: