Introduction

In this article, I will demonstrate 3 different ways to call server side method written in C# (ASP.Net) from client side using JQuery AJAX.

Background

Everyone knows that we use AJAX in any website in order to improve performance. JQuery is the latest and most widely used JavaScript library at present. I have seen several sites using JQuery and was highly impressed with the functionalities it provides, so I thought to start with JQuery.

I have categorized invoking server methods from client side in 3 categories.

  1. Calling server methods without parameters and get response.
  2. Calling server methods with simple parameter (integer or string value) and get response.
  3. Calling server methods with complex (JSON object) parameter and get response.

There is very slight difference in these categories, but I found that people generally get stuck here and invest a lot of time in identifying the difference. Though I have attached a running sample with this article but I would suggest creating the sample as per the steps mentioned below to get everything clear.

Steps To Create Sample Apllication

Create an ASP.Net Website:

A1.JPG

After that create a folder names Scripts in the application and add reference of “System.Web.Extensions.dll”. (DLL is present in the sample code attached.)

Now add following JQuery files in Scripts folder:

  1. jquery-1.6.2 .js or jquery-1.6.2.min.js
  2. jquery.json-2.2.js or jquery.json-2.2.min.js

It preferred to us min version. You can get these files from sample or download from www.jquery.com.

Now add a new JavaScript file in Scripts folder in which we will write our script give it any name, I have named it “MyJQuery.js”.

Till now we have done initial setup. Now let us start coding.

MethodInvokeWithJQuery.aspx

Add reference of .js files in head section and add styles to be used.

MethodInvokeWithJQuery.aspx

Add reference of .js files in head section and add styles to be used.

MethodInvokeWithJQuery.aspx

Add reference of .js files in head section and add styles to be used.

<script type="text/javascript" language="javascript" src="Scripts/jquery-1.6.2.min.js"></script>

    <script type="text/javascript" language="javascript" src="Scripts/jquery.json-2.2.min.js"></script>

    <script type="text/javascript" language="javascript" src="Scripts/MyJQuery.js"></script>

<style type="text/css">
        body
        {
            font-family:Arial;
            font-size:.93em;
        }
        
        #tblAjaxDemo p
        {
            border:1px solid #EEE;
            background-color:#F0F0F0;
            padding:3px;
        }
        
        #tblAjaxDemo p span
        {
            color:#00F;
            display:block;
            font:bold 21px Arial;
            float:left;
            margin-right:10px;
        }
    </style>

Now add controls. I have added 3 buttons and 3 div elements on this page as follows.

<div>
<h1>
Demo page: Server Side Method
Call Demo using JQuery and ASP.Net
</h1>
<p>
This page is a demo for calling
server side methods using ajax capabilities of jquery
.
</p>
<p style="margin: 20px 0; background-color: #EFEFEF; border:
1px solid #EEE; padding: 3px;">
Author: Praveen Meghwal
</p>
<table id="tblAjaxDemo" width="100%" cellpadding="1" cellspacing="0" border="0">
<tr style="height: 10px;">
<td colspan="2" align="right">
 
</td>
</tr>
<tr>
<td colspan="2">
<p>
<span>1</span>This is
button will call server side method from JQuery and get response
from server.
</p>
</td>
</tr>
<tr valign="top">
<td style="width: 30%;">
<asp:Button ID="btnTest" runat="server" Text="Click Me" />
</td>
<td style="width: 70%;">
<div id="myDiv" style="font-family:
Arial; color: Red;">
</div>
</td>
</tr>
<tr>
<td colspan="2">
<hr style="size: 2; color: Navy;" />
</td>
</tr>
<tr style="height: 20px;">
<td colspan="2">
 
</td>
</tr>
<tr>
<td colspan="2">
<p>
<span>2</span>This is
button will call server side method from JQuery along with
parameter and get
response from server. In this approach only numeric value parameters
are accepted. Here
I am passing numeric value 2 as parameter.
</p>
</td>
</tr>
<tr valign="top">
<td>
<asp:Button ID="btnTest2" runat="server" Text="Click Me" />
</td>
<td>
<div id="myDiv2" style="font-family:
Arial; color: Red;">
</div>
</td>
</tr> 
<tr>
<td colspan="2">
<hr style="size: 2; color: Navy;" />
</td>
</tr>
<tr style="height: 20px;">
<td colspan="2">
 
</td>
</tr>
<tr>
<td colspan="2">
<p>
<span>3</span>This is
button will call server side method from JQuery sendig complex
datatype (JSON
object) to server and get response from server.
</p>
</td>
</tr>
<tr valign="top">
<td>
<asp:Button ID="btnTest3" runat="server" Text="Click Me" />
</td>
<td>
<div id="myDiv3" style="font-family:
Arial; color: Red;">
</div>
</td>
</tr>
</table>
</div > 

We are done with the aspx stuffs; now let us move to .cs file (i.e. C# code).

MethodInvokeWithJQuery.aspx.cs

In MethodInvokeWithJQuery.aspx.cs, I have added 3 web methods which we will invoke from client side using JQuery. I have also added a class “Employee” which can be considered as server side replica of JavaScript object we are using in this demo. There is one more method which will convert client side complex object to server side equivalent.

Employee class: This class is created to simulate JavaScript object passed from client side.

public class Employee
{
private
string _firstName;
private
string _lastName;
private
string _technology;
private
int _age;
public string FirstName
{
get
{ return _firstName; }
set
{ _firstName = value; }
}
public string LastName
{
get
{ return _lastName; }
set
{ _lastName = value; }
}
public string Technology
{
get
{ return _technology; }
set
{ _technology = value; }
}
public int Age
{
get
{ return _age; }
set
{ _age = value; }
}
}

WebMethods: These methods will be invoked from client side using jQuery. In order to add WebMethod attributes to the method add "using System.Web.Script.Services;" in namespace.

[WebMethod]
public static string
MethodWithNoParameter()
{
return "Message from server.";
}
[WebMethod]
public static string
MethodWithNumericParameter(string strParam)
{
return "Parameter sent to server from client side is "
+ strParam;
}
[WebMethod]
public static string
MethodWithComplexParameter(object jsonParam)
{
Employee
objEmployee = GetEmployee(jsonParam);
return "Parameter sent to server from client side as
follows:<br/>First Name => " + 
objEmployee.FirstName + "<br/>Last Name => " +
objEmployee.LastName + "<br/>Technology
=> " + 
objEmployee.Technology + "<br/>Age => " +
objEmployee.Age;
}

GetEmployee Method: This method will parse the JavaScript object to server side equivalent.

public static Employee
GetEmployee(object employee)
{
Employee
objEmployee = new Employee();
Dictionary<string, object>
tmp = (Dictionary<string, object>)order;
object
objFirstName = null;
object
objLastName = null;
object
objTechnology = null;
object
objAge = null;
tmp.TryGetValue("FirstName", out
objFirstName);
tmp.TryGetValue("LastName", out
objLastName);
tmp.TryGetValue("Technology", out
objTechnology);
tmp.TryGetValue("Age", out objAge);
objEmployee.FirstName = objFirstName.ToString();
objEmployee.LastName =
objLastName.ToString();
objEmployee.Technology =
objTechnology.ToString();
objEmployee.Age = objAge.ToString();
return
objEmployee;
}

In this file we will add java script code required to run the application like: binding the event to the buttons placed on the aspx page and setting the Ajax attributes required to invoke the server side methods.

Following is the JavaScript code:

var Employee
= function(fName,
lName, technology, age) 
{
this.FirstName
= fName;
this.LastName
= lName;
this.Technology
= technology;
this.Age
= age;
}
$(document).ready (
function () 
{
try
{
$('#btnTest').click
(
function () 
{
$.ajax (
{
type: "POST",
url: "MethodInvokeWithJQuery.aspx/MethodWithNoParameter",
data: "{}",
contentType: "application/json;
charset=utf-8",
dataType:
"json",
async: true,
cache: false,
success: function (msg) 
{
$('#myDiv').text(msg.d); 
},
error: function (x, e)
{
alert("The call to the server side
failed. " + x.responseText);
}
}
);
return false;
}
);
$('#btnTest2').click
(
function () 
{
$.ajax (
{
type: "POST",
url: "MethodInvokeWithJQuery.aspx/MethodWithNumericParameter",
data: "{'strParam' : 2}",
contentType: "application/json;
charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function
(msg) 
{
$('#myDiv2').text(msg.d); 
},
error:
function (x, e)
{
alert("The call to the server side
failed. " + x.responseText);
}
}
);
return false;
}
);
$('#btnTest3').click
(
function () 
{
var jsEmp = new
Employee("Praveen", "Meghwal", "Microsoft
Dotnet", 31);
var jsonText = $.toJSON(jsEmp);
$.ajax (
{
type: "POST",
url: "MethodInvokeWithJQuery.aspx/MethodWithComplexParameter",
data: "{'jsonParam' : " + jsonText + "}",
contentType: "application/json;
charset=utf-8",
dataType: "json",
async:
true,
cache: false,
success: function (msg) 
{
$('#myDiv3').html(msg.d); 
},
error: function (x, e)
{
alert("The call to the server side
failed. " + x.responseText);
}
}
);
return false;
}
);
}
catch(err)
{
alert(err);
}
}
);

Now let us see code line by line.

In the top we have defined the JavaScript object Employee, which has 4 properties same as server side.

var Employee
=function(fName,
lName, technology, age) 
{
this.FirstName
=fName;
this.LastName
=lName;
this.Technology
=technology;
this.Age
=age;
}

Then we have used document.ready() function to perform operations on the controls once DOM for the page is available for operation.

$(document).ready();

In document.ready() function I have bind click events for all the 3 buttons. While binding I have used ajax() method of JQuery. In this method I have specified different parameter values including which server side method to invoke.

$.ajax  (
{
type: "POST",
url: "MethodInvokeWithJQuery.aspx/MethodWithNoParameter",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function
(msg) 
{
$('#myDiv').text(msg.d);
},
error: function (x, e)
{
alert("The call to the
server side failed. "+ x.responseText);
}
}
);

Above is the ajax method declaration for first button. Here in url property we specify the server side method name to invoke followed by page name. In data property we set the parameter values to be passed to the method. In case of first button we are not passing any parameter so we just added "{}" here. But in case of second and third button you will see I have used [data: "{'strParam' : 2}"] and [data: "{'jsonParam' : " + jsonText + "}"] respectively.

Now let us see what is the difference between second and third approach?

Second approach will work fine if you pass inbuilt data type value as parameter to it. For example: [data: "{'strParam' : 2}"] and [data: "{'strParam' : ‘string value’}"].

Now what if we want to pass user defined JavaScript objects as parameter, for this scenario we will have to use third approach i.e. [data: "{'jsonParam' : " + jsonText + "}"]. Here variable jsonText is string representation of JavaScript object we have created. See the binding code for third button, there I have written following lines

var jsEmp = new Employee("Praveen",
"Meghwal", "Microsoft Dotnet", 31);
var jsonText =
$.toJSON(jsEmp);

Here we have used $.toJSON () method of JQuery in order to convert it to equivalent string representation. In order to use this method I have added reference to JQuery file "jquery.json-2.2.min.js." We can also use JSON.stringify() method, but here JSON is only available if there is inbuilt JSON support in the browser.

In success property we specify the client script to call after successful completion of asynchronous call to the server. In error property we specify client script to call in case any error occurs.

We are done with the coding part. Now run the application, check whether code is running properly or not. If you get an alert displaying the error, got to web.config file and check System.Web tag under configuration. It should look like:

<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing
this file you can use the 
    web admin tool to configure settings for
your application. Use
    the Website->Asp.Net Configuration
option in Visual Studio.
    A full list of settings and comments can be
found in 
    machine.config.comments usually located in 
   
\Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
  <appSettings/>
  <connectionStrings/>
  <system.web>
    <!--
            Set compilation
debug="true" to insert debugging 
            symbols into the compiled page.
Because this 
            affects performance, set this value
to true only 
            during development.
        -->
    <compilation
debug="true">
      <assemblies>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
    <!--
            The <authentication> section
enables configuration 
            of the security authentication mode
used by 
            ASP.NET to identify an incoming
user. 
        -->
    <authentication
mode="Windows"/>
    <!--
            The <customErrors> section
enables configuration 
            of what to do if/when an unhandled
error occurs 
            during the execution of a request.
Specifically, 
            it enables developers to configure
html error pages 
            to be displayed in place of a error
stack trace.
 
        <customErrors
mode="RemoteOnly"
defaultRedirect="GenericErrorPage.htm">
            <error
statusCode="403" redirect="NoAccess.htm" />
            <error
statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    <!-- Start Settings for
AJAX-->
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
    <!-- End Settings for AJAX-->
  </system.web>
</configuration>

If your web.config is not as displayed, add inner tags in httpHandlers and httpModule tags as specified in the web.config.

Output

A2.JPG

Points of Interest

I have wasted a lot of time for implementing server method call with complex parameter. I search on net for help every where I found to pass json text returned from $.toJSON(jsEmp) as parameter to server side, I tried it but this did not work for me. Then I thought to use technique used in second aproach for sending inbuilt type parameter to server side. I thought that function $.toJSON(jsEmp) is converting JSON to string representation so second approach should work, I tried [data: "{'jsonParam' : " + jsonText + "}" ]and got succedded.

History

First version

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"