Archive

Archive for the ‘JavaScript/jQuery/JSON/Ajax’ Category

Load ASP.Net User Control Dynamically Using jQuery

October 10, 2009 5 comments

Today we will explore the way of loading ASP.Net user control at run time using jQuery. jQuery has one method load(fn) that will help here. This load(fn) method has following definition.

load (url, data, callback): A GET request will be performed by default – but if any extra parameters are passed, then a POST will occur.
url (string): URL of the required page
data (map – key/value pair): key value pair data that will be sent to the server
callback (callback method): call back method, not necessarily success

Now comes custom HttpHandler that will load the required user control from the URL given by this load(fn) method. We all know that it is either in-built or custom HttpHandler that is the end point for any request made in ASP.Net.

Let’s see by example. In the ASP.Net application, add one aspx page and user control. Then, add one more class derived from IHttpHandler. The aspx html markup will look something like this.

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Load ASP.Net User Control</title>
<script src=”jquery-1.2.6.js”></script>
<script>
$(document).ready(function() {
$(“#BtnLoadUserCtrl”).click(function() {
$(“#UserCtrl”).load(“SampleUserCtrl.ascx”);
});
});
</script>
</head>
<body>
<form runat=”server”>
<div>
<br />
<input value=”Load User Control” /> <br />
<div id=”UserCtrl”></div>
</div>
</form>
</body>
</html>

The code is quite readable. On the click event of BtnLoadUserCtrl button, SampleUserCtrl.ascx user control is being tried to load in the <div> element having id UserCtrl.

Then, write our custom Httphandler called jQueryHandler as below.

public class jQueryHandler:IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// We add control in Page tree collection
using(var dummyPage = new Page())
{
dummyPage.Controls.Add(GetControl(context));
context.Server.Execute(dummyPage, context.Response.Output, true);
}
}

private Control GetControl(HttpContext context)
{
// URL path given by load(fn) method on click of button
string strPath = context.Request.Url.LocalPath;
UserControl userctrl = null;
using(var dummyPage = new Page())
{
userctrl = dummyPage.LoadControl(strPath) as UserControl;
}
// Loaded user control is returned
return userctrl;
}

public bool IsReusable
{
get { return true; }
}
}

Do not miss to add this HttpHandler in the web.config.

<httpHandlers>
<add verb=”*” path=”*.ascx” type=”JQUserControl.jQueryHandler, JQUserControl”/>
</httpHandlers>

This web.config configuration tells that jQueryHandler will process request for file type having .ascx extension and methods all (GET, POST, etc). The type attribute value is something like:
type=”Namespace.TypeName, Assembly name where Handler can be found”

Now we are ready to test our sample. Run the page, and see on the click of button, the sampleusertCtrl.ascx is loaded.

I hope we can now extend this concept to fit any such programming requirement in future.
Happy Coding!

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.

JSON and JavaScript

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.

Let’s see one JSON format data.

{
“Asia”:”China”,
“Africa”:”Zimbabwe”,
“North America”:”Canada”,
“South America”:”Brazil”,
“Antarctica”:”Netherlands”,
“Europe”:”Russia”,
“Australia”:”Sydney”,
“Cities”:[
“Shanghai”,
“Moscow”,
“Johannesburg”,
“Vancouver”,
“New York”,
“Kathmandu”,
“Singapore”
]
}

If the same data were to be represented in XML, then the structure would like as:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<CountryCities>
<Asia>China</Asia>
<Africa>Zimbabwe</Africa>
<NorthAmerica>Canada</NorthAmerica>
<SouthAmerica>Brazil</SouthAmerica>
<Antarctica>Netherlands</Antarctica>
<Europe>Russia</Europe>
<Australia>Sydney</Australia>
<Cities>
<City>Shanghai</City>
<City>Moscow</City>
<City>Johannesburg</City>
<City>Vancouver</City>
<City>New York</City>
<City>Kathmandu</City>
<City>Singapore</City>
</Cities>
</CountryCities>

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.

According to http://www.json.org/fatfree.html, the object notation in JSON can be done in two ways: Unordered key-value pairs and Ordered lists.

In the example above, the continent and country names are unordered key-value notation.
“Asia”:”China”,
“Africa”:”Zimbabwe”,
“North America”:”Canada”,
“South America”:”Brazil”,
“Antarctica”:”Netherlands”,
“Europe”:”Russia”,
“Australia”:”Sydney”,

And the city names are ordered list.
“Cities”:[“Shanghai”, “Moscow”, “Johannesburg”, “Vancouver”, “New York”, “Kathmandu”, “Singapore”]

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.

<%@Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”JsonAndJS._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>Json and JavaScript</title>
<script language=”javascript” type=”text/javascript”>
var JsonString =
‘ {‘ +
‘ “Asia”: “China”,’ +
‘ “Africa”: “Zimbabwe”,’ +
‘ “NorthAmerica”: “Canada”,’ +
‘ “SouthAmerica”: “Brazil”,’ +
‘ “Antarctica”: “Netherlands”,’ +
‘ “Europe”: “Russia”,’ +
‘ “Australia”: “Sydney”,’ +
‘ “Cities”:  [‘ +
‘             “Shanghai”,’ +
‘             “Moscow”,’ +
‘             “Johannesburg”,’ +
‘             “Vancouver”,’ +
‘             “New York”,’ +
‘             “Kathmandu”,’ +
‘             “Singapore”‘ +
‘             ]’ +
‘}’;
function ListJsonValues() {
var CountryCities = eval(“(” + JsonString + “)”);
var CityNames = “<br />” + “City Names: ” + “<br />”;
for (var j = 0; j < CountryCities.Cities.length; j++) {
CityNames += “City: ” + (j + 1) + ” – ” + CountryCities.Cities[j] + “<br />”;
}
document.getElementById(‘dvPopularCities’).innerHTML = CityNames;
var CountryNames = “”;
CountryNames = “Countries: ” + “<br/>” + CountryCities.Asia + ” – ” + CountryCities.Africa + ” – ”
+ CountryCities.NorthAmerica + ” – ” + CountryCities.SouthAmerica + ” – ” + CountryCities.Antarctica + ” – ”
+ CountryCities.Europe + ” – ” + CountryCities.Australia + “<br />”;
document.getElementById(‘dvCountryList’).innerHTML = CountryNames;
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<input id=”BtnList” type=”button” value=”List Country and City Names” onclick=”ListJsonValues();” />
</div>
<div id=”dvCountryList”>
</div>
<div id=”dvPopularCities”/>
<br />
</form>
</body>
</html>

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.