jQuery, JSON and ASP.Net Web Service

Today we will see a simple example of jQuery, JSON and ASP.Net Web Service. We will mainly see how to consume ASP.Net web service web methods using both jQuery and JavaScript and see how to handle DateTime object result. Also, how jQuery can be used to call a web method by passing arguments values.

We know JSON type lacks Date/Time literal because JavaScript too does not have Date/Time literal directly. I think JavaScript author was smart enough to leave Date/Time literal! As Date/Time is a complex subject, that should be better left for programmers who write code to interact with servers that have different running time zones, and we know JavaScript is a client-side scripting language.

Let’s see how to handle this with examples. Write a simple web service as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Serialization;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace JsonAndScriptSvc
{
/// <summary>
/// Summary description for WebServerDate
/// </summary>
[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script,
// using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebServerDate : System.Web.Services.WebService
{
//
private JsonDateSez objJson = null;
public WebServerDate()
{
objJson = new JsonDateSez();
}
[WebMethod]
public object GetServerDate()
{
JavaScriptSerializer serz = new JavaScriptSerializer();
return serz.Serialize(objJson);
}
[WebMethod]
public Int32 GetSumResult(Int32 xValue, Int32 yValue)
{
return (xValue + yValue);
}
}

public class JsonDateSez
{
public DateTime JsonSerzDate
{
get { return new DateTime(2009, 9, 17); }
}
}
}

Then, add one Default.aspx page whose mark-up code looks like this:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”JsonAndScriptSvc._Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>JavaScript and JavaScriptSerializer</title>
<script type=”text/javascript” language=”javascript” src=”JSWebService.js”></script>
</head>
<body>
<form id=”frmJson” runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”>
<Services>
<asp:ServiceReference Path=”~/WebServerDate.asmx” />
</Services>
</asp:ScriptManager>
<div>
<input id=”BtnFetchDate” type=”button” value=”Check Server Date” onclick=”ServerDate();”/>
<br />
</div>
</form>
</body>
</html>

The onClick() event of BtnFetchDate button will call ServerDate() method in JSWebService.js file. This js file has two methods as:

function ServerDate() {
JsonAndScriptSvc.WebServerDate.GetServerDate(ReceivedDate);
}
function ReceivedDate(result) {
var svrdt = Sys.Serialization.JavaScriptSerializer.deserialize(result);
alert(“Result in Json Format: ” + result + “\n” + “Result desired: ” + svrdt.JsonSerzDate);
}

Once clicked, we may see result as shown in figure below.

JSON-WebService

We saw how JavaScriptSerializer class helped to get the desired date-time result.

Similarly, we can see jQuery based example similar to above one. Let’s add another JQryPage.aspx page whose mark-up may look like this:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”JQryPage.aspx.cs” Inherits=”JsonAndScriptSvc.JQryPage” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>JQuery and Web Service</title>
<script type=”text/javascript” language=”javascript” src=”jquery-1.2.3.min.js” />
<script type=”text/javascript” language=”javascript” src=”JSWebService.js”></script>
<script type=”text/javascript” language=”javascript”>
/* jQuery calling webmethod to fetch server date-time values */
function JQueryWebMethod() {
$.ajax({
type: “POST”,
url: “WebServerDate.asmx/GetServerDate”,
data: “{}”,
contentType: “application/json;charset=utf-8”,
dataType: “json”,
success: function(result) {
alert(“Result in Json Format: ” + result.d);
},
error: function(request, status, throwerror) {
alert(status);
}
});
}
/* jQuery calling webmethod by passing two arguments */
function JQuerySumResultWebMethod() {
$.ajax({
type: “POST”,
url: “WebServerDate.asmx/GetSumResult”,
data: “{‘xValue’:’10’,’yValue’:’15’}”,
contentType: “application/json;charset=utf-8”,
dataType: “json”,
success: function(result) {
alert(result.d);
},
error: function(request, status, throwerror) {
alert(status);
}
});
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”>
<Services>
<asp:ServiceReference Path=”~/WebServerDate.asmx” />
</Services>
</asp:ScriptManager>
<div>
<input id=”BtnJQry” type=”button” value=”jQry Check Server Date” onclick=”JQueryWebMethod();”/>
<br /><br />
<input id=”BtnSumResult” type=”button” value=”jQry Sum Result” onclick=”JQuerySumResultWebMethod();”/>
</div>
</form>
</body>
</html>

Run this page, click BtnJQry button to see the result of Date/Time. We may see the same raw result that we received in JavaScript before deserializing ‘result’ object using JavaScriptSerializer class. Click other button called BtnSumResult will get the sum result from web method by passing two arguments values.

The documentation of $.ajax() global method can be found at http://docs.jquery.com/Ajax/jQuery.ajax. However, we should remember type, url, data, contentType and dataType key values when constructing parameters for $.ajax() global method.

Thus, we saw jQuery, JSON and ASP.Net Web Service example.

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment