Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calling Server Side function from Client Side Script

0.00/5 (No votes)
8 Jun 2012 2  
Calling Server Side function from Client Side Script

Introduction

The Article is about how you can call your code behind file function i.e server side written function from your client side code i.e using jQuery. Recently I got requirement in my project that I have to check that ApplicationCode i.e Value entered by user is already available in database or not i.e unique value. Output of the will look like as below if record exists its shows error "Record exists" otherwise it doesn't display any record.

Now in following post I am going to discuss about the what are the prerequisite need and why to use that. 

Server Code

Below method get called from the client side script, as you can see there are some changes in the method attribute, declaration and definition which I am going to discuss

[WebMethod]
    public static string IsExists(string value)
    {
        //code to check uniqe value call to database to check this
        return "True";
    }

WebMethod Attribute

Attached WebMethod attribute with Public method indicates that the method exposed as part of the XML Web service. The attribute tells .NET that a particular public method is exposed as a web-callable method. To make use of this attribute you need to make use of System.Web.Services You can read about this attribute at : WebMethodAttribute Class

Static method 

Static method is not associated with the instance of the class which get called by using only classname.methodname() i.e no need to create instance. So that's why I marked method as static one. It cannot interact with the instance properties and methods of your Page class, because a page method call creates no instance of the Page or any of its controls. Page methods are roughly equivalent to shorthand for standalone web services.

.CS file

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;//needed for the webmethod attribute
public

partial class _Default : System.Web.UI.Page
{
     protected void Page_Load(object sender, EventArgs e)
     {
          if (!IsPostBack)
               txtData.Attributes.Add("onblur", "focuslost()");
     }

     [WebMethod]
     public static string IsExists(string value)
     {
          return "True";
     }
}

in above code I have registered client event with onblur and attahced function focuslost.

Client Code on .ASPX page code jQuery .ajax() call

To called method from the client side code I made use of the jQuery function called ajax to get more details about this function you can read about my blog post : Jquery Ajax Calling functions

function IsExists(pagePath, dataString, textboxid, errorlableid) {
 
$.ajax({
     type:"POST",
     url: pagePath,
     data: dataString,
     contentType:"application/json; charset=utf-8",
     dataType:"json",
     error:
          function(XMLHttpRequest, textStatus, errorThrown) {
               $(errorlableid).show();
               $(errorlableid).html("Error");
          },
     success:
          function(result) {
               var flg = true;
               if (result != null) {
                    flg = result.d;
                    if (flg == "True") {
                         $(errorlableid).show();
                    }
                    else {
                         $(errorlableid).hide();
                    }
          }
     }
    });
}

In client script : 

As I have to check code is exists or not I attached focusout() event with my textbox control, so when the focus get lost it make ajax call to the TextChanged event of code behind file.

url -       Contains path of the page which is get called from the client side code i.e from asppage.

data -    Data sent to server from the client it basically json string. contentType - Content type sent to server.  

dataType - Expected data format from server

error -  Called when call to server method fails

success - Called when call to server method is successes and return data from called method can be processed in this method  

.Aspx page code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Async="true" Inherits="_Default" %>

<title></title>
<script src="JavaScript/jquery.js" type="text/javascript">
</script>
<script type="text/javascript">
function IsExists(pagePath, dataString, textboxid, errorlableid) {
 
$.ajax({
     type:"POST",
     url: pagePath,
     data: dataString,
     contentType:"application/json; charset=utf-8",
     dataType:"json",
     error:
          function(XMLHttpRequest, textStatus, errorThrown) {
               $(errorlableid).show();
               $(errorlableid).html("Error");
          },
     success:
          function(result) {
               var flg = true;
               if (result != null) {
                    flg = result.d;
                    if (flg == "True") {
                         $(errorlableid).show();
                    }
                    else {
                         $(errorlableid).hide();
                    }
          }
     }
    });
}
function focuslost() {
     var pagePath = window.location.pathname + "/IsExists";
     var dataString = "{ 'value':'" + $("#<%= txtData.ClientID%>").val() + "' }";
     var textboxid = "#<%= txtData.ClientID%>";
     var errorlableid = "#<%= lblError.ClientID%>";
     IsExists(pagePath, dataString, textboxid, errorlableid);
}
</script>


     
          <form id="form1" runat="server">
<asp:label text="Enter unique value : " runat="server" id="lbl" />                                         
               <asp:textbox runat="server" id="txtData" />
               

<div style="display: none;"  runat="server" id="lblError">
Record exsits</div>
</form>
as in above code focuslost function get call IsExists function which in-turn call the serverside function and inform the entered value is unique or not.  

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here