Calling Server Side Method from Client Side using JQuery in ASP.NET

No.of Views831
Bookmarked0 times
Downloads 
Votes0
By  pranay rana   On  21 Jan 2012 08:01:59
Tag : ASP.NET , How to
Today, I tried find a best solution for call server side method in the client side do some task in the page. But unfortunately, I could not any best solution. Hence decided to article about it. The purpose of article is going to explore that how to call a server side method from the client side using jQuery in the ASP.NET 4.0.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Today, I tried find a best solution for call server side method in the client side do some task in the page. But unfortunately, I could not any best solution. Hence decided to article about it. The purpose of article is going to explore that how to call a server side method from the client side using jQuery in the ASP.NET 4.0.

The sample output of the will look like as below if record exists its shows error "Record exists" otherwise it doesn't display any record. 

Image Loading

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 aspx page.
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 id="lbl" runat="server" text="Enter unique value : "></asp:label>                                        
               <asp:textbox id="txtData" runat="server"></asp:textbox>
                
 
<div id="lblError" runat="server" style="display: none;">
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. That's all and enjoy it.

 
Sign Up to vote for this article
 
About Author
 
pranay rana
Occupation-CEO
Company-GMind Solusion
Member Type-Senior
Location-India
Joined date-08 Jan 2011
Home Page-http://pranayamr.blogspot.com
Blog Page-http://pranayamr.blogspot.com
Hey, I am Pranay Rana, working as a Senior Software engineer in mid-size company located in ahmedabad. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 4.3 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 me on my blog - http://pranayamr.blogspot.com/ StackOverFlow - http://stackoverflow.com/users/314488/pranay My CV :- http://careers.stackoverflow.com/pranayamr
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top