Asp.Net How to Call Code Behind or Server Side Function from JavaScript in C# and VB.Net

In This Tutorial I will explain how to call code behind method or function from JavaScript in asp.net using c# and vb.net with  good example and asp.net call code behind or server side method from JavaScript using c# and vb.net.

And how to call code behind method from JavaScript in asp.net using c# and vb.net with Good example. Using asp.net ajax scriptmanager property “EnablePageMethods = True” we can call server side method  in c# and vb.net.

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 call code behind method or function from JavaScript we need to write the following code in aspx page which is given below.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="head" runat="server">
<title>call server side function from javascript in asp.net</title>
<script type="text/javascript" language="javascript">
function democallservermethod() {
var Name = $get("txt_Name").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:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Enter Name of Person: <asp:TextBox ID="txt_Name" runat="server"></asp:TextBox>
<asp:Button ID="btnClick" runat="server" Text="Click" OnClientClick     ="democallservermethod()" />
</div>
</form>
</body>
</html>

Now open code behind file and write following code

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";
}

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"
End Function
End Class

Output
Call Code Behind or Server Side Function from JavaScript in C# and VB.Net

Previous
Next Post »

If you have any kind of question about any post, Feel free to ask.You can simply drop a comment below post. Your feedback and suggestions will be highly appreciated. ConversionConversion EmoticonEmoticon