V24s

"Get Updates : Subscribe to our e-mail newsletter to receive updates........" "Good Luck frnds" Admission 2019 Application Form 2019 Colleges Entrance Exam 2019 Results 2019 Notification 2019 University Educational Jobs 2019 Government Jobs 2019

Search This Blog v24s guys

15 April, 2013

Call Server Side Function from JavaScript in Asp.net Ajax

Introduction

Here I will explain how to call server side methods or functions from 
JavaScript in asp.net.

Description: 
   
In previous posts I explained How to Call Asp.net Page methods in jQuery, 
JavaScript restrict to enter only numbers, JavaScript Redirect to another page after some time delay, JavaScript Set Default home page in browsers and many articles relating to JavaScript, Asp.net. Now I will explain how to call server side methods or functions from JavaScript in asp.net.

By using asp.net Ajax scriptmanager we can call server side methods from JavaScript 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 Aspdotnet-Suresh.com ";
}
VB.NET Code

Imports System.Web.Services
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
<WebMethod()> _
Public Shared Function GetCurrentDate(ByVal name As String) As String
Return ("Hi " & name) + Environment.NewLine & "Welcome to Aspdotnet-Suresh.com "
End Function
End Class
Demo

No comments:

Popular Posts

Recent Posts

Google Analytics