Thursday 18 July 2013

Call Server Side Function from JavaScript in Asp.net Ajax

By using asp.net Ajax scriptmanager we can call server side methods from java script  for that we need to set property EnablePageMethods="True" in asp,net Ajax  scriptmanager. 

To implement this one you need to write the following code in your page

<htmlxmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>call server side method from javascript in asp.net</title>
<script type="text/javascript"language="javascript">
function callservermethod() {
var name = $get("txtName").value;
PageMethods.GetCurrentDate(name, OnSuccess, OnFailure);
}
function OnSuccess(result) {
if (result) {
alert(result);
}
}
function OnFailure(error) {

}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManagerID="ScriptManager1" runat="server"EnablePageMethods="True">
</asp:ScriptManager>
Enter Name of Person: <asp:TextBoxID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnClick" runat="server"Text="Click" OnClientClick="callservermethod()" />
</div>
</form>
</body>
</html>
After that add following namespace in code behind

C# Code


using System;
using System.Web.Services;
Once namespaces added then write the following code in code behind


[WebMethod]
public static string GetCurrentDate(string name)
{
return "Hi " + name + Environment.NewLine + "Welcome to sreenivas.net";
}

No comments:

Post a Comment