Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to call server side function from client side script in ASP.NET

Author: Jeff Nava
Download Source Code : 1307_ServerSideFunctionFromClientSide.zip

In this article, you will see how we can call server side function from client side JavaScript function in ASP.NET. You can download source code.

 

 

In the normal scenario, functions written in server side languages in ASP.NET are called from the server side but there can be a situation when you need to call server side function from client side script. I will explain in this article that how you will be able to do so.
 
You can call a server side function by using JavaScript or using jQuery in your ASP.NET application. This article will focus on JavaScript to call a server side function with AJAX functionality. It will also need to have a Web Method on server side to call from JavaScript. We will use Page Method in JavaScript to call this Web Method.  A Page Method is actually a public static server side method that can be called from client side.   

 

  1. Open Visual Studio 2010
  2. File > New > Website
  3. Visual basic or Visual C# > ASP.NET Empty Web Site
  4. Website > Add New Item > Web Form
  5. Add a ScriptManger control in your aspx page.

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

     
  6. Add code below in aspx page

    <asp:Label ID="Label1" runat="server" Text="Enter Product ID:"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Get Product Name" OnClientClick="getProductName()" />
    <br />
    <asp:Label ID="lblProductName" runat="server" ></asp:Label>


    I have added a Label with text and a Label to show result, a Text Box to enter ID of the product and a button. I have added the onClientClick attribute and set it to JavaScript function. We will see this function later in the article.
     
  7. Now open code behind file and Include following namespaces

    C#
     
    using System.Web.Services;
    using System.Data;
    using System.Data.SqlClient;
     
    VB.NET
     
    Imports System.Web.Services
    Imports System.Data
    Imports System.Data.SqlClient

     
  8. Write following function in code behind file

    C#
     
    [WebMethod]
    public static string GetProductName(int productID) {
        string sql = "SELECT ProductName FROM Products WHERE ProductID =" + productID;
        SqlConnection con = new SqlConnection("Data Source=source;Initial Catalog= NORTHWND;Integrated Security=True");
     
        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        string productName = dt.Rows[0]["ProductName"].ToString();
        return productName;
    }
     
    VB.NET
     
    <WebMethod()> _
    Public Shared Function GetProductName(ByVal productID As Integer) As String
        Dim sql As String = "SELECT ProductName FROM Products WHERE ProductID =" & productID
        Dim con As New SqlConnection("Data Source=source;Initial Catalog=NORTHWND;Integrated Security=True")
        Dim cmd As New SqlCommand(sql, con)
        Dim da As New SqlDataAdapter(cmd)
        Dim dt As New DataTable()
        da.Fill(dt)
        Dim productName As String = dt.Rows(0)("ProductName").ToString()
        Return productName
    End Function
     
    You must have to declare this function as WebMethod to call it from JavaScript. As you can see I have declared it in my code. This function must also be declared as public static function so that we can access it from client side. The function is making a connection to NORTHWIND database in SQL Server and returning product name of the Product ID which we will get from TextBox. You need to make connection to your server if you want to use this function.
     
  9. Now write below JavaScript code in your aspx page in between <body> tag

    <script type="text/javascript">
        function getProductName() {
            var prodID = document.getElementById('<%= TextBox1.ClientID %>');
            var prodName = document.getElementById('<%= lblProductName.ClientID %>');
            PageMethods.GetProductName(prodID.value, onSuccess, onFailure);
        }
        function onSuccess(result, prodName, methodName) {
            prodName.value = result;
        }
        function onFailure(error, userContext, methodName) {
            alert(error.get_message());
        }
     
    </script>


    In JavaScript code, I have written a function “getProductName” that is mentioned in the “onClientClick” attribute of the Button control. This JavaScript function gets the TextBox and Label controls by using getElementById() method of “document”. Then I have called the server side function by using PageMethod attribute. I have passed three parameters in the function, first one is the value of the Textbox second and third are onSuccess and onFailure respectively. “onSuccess” will call the “onSuccess()” function when the call to the server side function is successful and “onFailure” will call the “onFailure()” function when the call to the server side function is fail. In “onSuccess()” function, I have assigned result to label. In “onFailure()” function I have just displayed the failure message.
     
  10. Now see the web site in browser. Provide the ID in Textbox and see the product name.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to use Take/TakeWhile and Skip/SkipWhile Operators in LINQ

Disclaimer - Privacy
© 2002-2017 DevASP.net