Archive

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.

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.

We all know that XML is widely used in applications that leverage service-oriented architectures for sending and receiving data. But it cannot always be an ideal candidate to carry light-weight data. So JSON like format is increasingly becoming popular these days. JSON (JavaScript Object Notation) is a subset of the object literal notation of JavaScript. JSON is a text format that is completely language independent. When some data is JSON formatted, it is concise, human readable and easy to write.

As compared to XML format, we see JSON is more concise, clear and has higher data-to-markup ratio. That’s why; JSON can be a better candidate for data interchange in client and server communication. However, we should not take JSON as a document format. Also, it is not a markup language. It is a subset of the object literal notation that JavaScript supports natively.

The key is always represented in string type, while values may be any JSON types (string, number, Boolean, object, array and null).You may wonder why not date/time also. Because JavaScript also does not support date/time literal directly, instead JavaScript uses Date object. Se before representing any data in JSON format, one should also check for the compatible and supporting types. For .Net, we can see more about JSON types at http://msdn.microsoft.com/en-us/library/bb299886.aspx. There are plenty of open source tools and libraries that will help write and parse valid JSON text. Similarly, we can also validate the syntax check of JSON text using JSONLint. I think we may know about JSLint as well. It is a code quality tool and is used to validate JavaScript code.

Let’s come to an example of JSON and JavaScript. We will take the same JSON text in the example above to parse and convert into an object.

One should try this example to see the result.
We see how the eval() method of JavaScript is used to parse the JSON text and return an object to CountryCities variable object. The extra parenthesis in eval() method is used to treat the JSON text as expression. But since eval() always parses the input text blindly, we have to be careful about the nature of input text expression from both coding and security point of views. There are various open source libraries in JavaScript which provide parse methods to return valid object out of JSON text.

Seeing the ease and nature of JSON text in AJAX world, JSON is gaining popularity rapidly. Even its MIME media type is now formalized as application/json. JSON may be favored among programmers to make point to point integration and data exchange between browser client and web server, but not similar to XML where it has huge support of integration in SOA world. But yes, if the data is small, JSON is a good option.

Today we will see how ASP.Net Ajax callback feature can help us call methods defined in Web Service and ASP.Net page. ScriptService and ScriptMethod are two new attributes in ASP.Net Ajax framework library that helps calling web service and web page web methods respectively.
Let’s see it one by one in the following examples.

First, create a simple web service project called ASPAjaxService.asmx. Define a web method as given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace ASPAjaxService
{
/// <summary>
/// Summary description for ASPServiceMethods
/// </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 ASPServiceMethods : System.Web.Services.WebService
{
//
[WebMethod(true)]
public string WebServiceMethod()
{
return “Example: Consuming a web service using ASP.Net Ajax.”;
}
}
}
See the ScriptService attribute that is applied to Class declaration ASPServiceMethods. This indicates that a web service can be invoked from script. In fact, it provides a JavaScript proxy class corresponding to the web service in order to call the web service web methods. Now to test this service, let’s view our *.asmx in browser. Probably, we may see url as: http://localhost:49487/ASPAjaxService.asmx. The port number may vary, but we are now ready to test WebServiceMethod web method. Before this, change the url as: http://localhost:49487/ASPAjaxService.asmx/js and hit [Enter]. It will return a proxy code of JavaScript. We may save it to our project folder to see its details. This is result of ScriptService attribute.

Now, create a simple ASP.Net application and add this existing web service project to this application. Modify the Default.aspx markup as:

See the <asp:ScriptManager/> tag section. ServiceReference registers the web service mentioned in Path attribute for use in a web page. Path can only point to local web service, i.e.; in the same domain.

InlineScript value can be either true or false. Toggle its value, view Default.aspx in browser, view its html source and save it. Compare the size of two files. You will see a remarkable difference. When InlineScript is set to true, the proxy javascript code is generated and rendered directly in the page for each request. Due to this, the page can not be cached for similar request and page size is also larger.

But in our example, we have set this property to false and added src=”javascript_ajax_asp_net.js”. It has required functions to fulfil our purpose. But one may compare and see both the proxy and current *.js file. In this case, we can definitely benefit from browser caching and shorter page load time!

[WebMethod(true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static string WebMethodInPage()
{
//
return “I am in Page Method.”;
}
Run the page and call each web method. We are able to call ASP.Net page method due to ScriptMethod attribute for WebMethodInPage() method and EnablePageMethods=”true” in ScriptManager class property. ScriptManager.EnablePageMethods property when set to true enables public static web method in page to be called by javascript.