Click here to Skip to main content
15,867,938 members
Articles / Web Development / ASP.NET
Article

Calling Server Side function from Client Side Script

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
8 Jun 2012CPOL2 min read 65.5K   22   5
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
QuestionJavascript Location Pin
Pakesh Protihar25-Jun-13 23:01
Pakesh Protihar25-Jun-13 23:01 
QuestionBut how to call non static method from client side That returns the string value ??? Pin
chirag solanki 908518-Nov-12 20:26
chirag solanki 908518-Nov-12 20:26 
AnswerRe: But how to call non static method from client side That returns the string value ??? Pin
Pranay Rana8-Nov-12 23:21
professionalPranay Rana8-Nov-12 23:21 
General__doPostBack Pin
Member 475794318-Jul-12 17:35
Member 475794318-Jul-12 17:35 
SuggestionIsExists Pin
Vitaly Tomilov10-Jun-12 3:08
Vitaly Tomilov10-Jun-12 3:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.