Bind a CheckBox list from database using jQuery AJAX

Hi All,

I have seen many questions in the forums that how can we bind the CheckBox list from the database via Ajax. There could be many ways to do in an ASP.NET but I will be using the one of the most efficient options available .

In this post, I’ll be using jQuery Ajax to get the data from the server (that will be fetch the data from database) and then will create the CheckBox list dynamically.

Continue reading

document.ready vs Javascript onload

It is a small post, who are new to jQuery or just started working with jQuery. As we all know that jQuery is Client side library and provides a wrapper over JavaScript . One of the very good things about jQuery that it runs seamlessly in all leading browsers while you must have faced many issues related to the browsers when you work with JavaScript.

So let’s jump to the topic. What is the difference between let’s first go by an example.

I have created a simple default.aspx page in my asp.net empty application and added few images and put the path from web and added few text. Now I put a general alert and called it on load method of window as

<script type="text/javascript" language="javascript">
        window.onload = OnLoad();
        function OnLoad() {
            alert('I am called by window.onload');
        }
    </script>

Now again I tried to change the code to jQuery document.ready function. And used the code as

$(document).ready(function () {
              OnLoad();
         });
        function OnLoad() {
            alert('I am called by document.ready');
        }

and when I ran it. I got the alert very fast. So what I wanted to point out here that jQuery’s document.ready runs much earlier the JavaScript onload. Why?

document.ready get’s fired as soon as DOM is ready and registered with the browser. It does not wait for the all the resources to get loaded. It allows us some very cool showing, hiding and other effects as soon as user sees the first element on the page.

While Javascript’s onload method gets fired only when all content of the webpage and image, iframes etc get loaded in browser then onload get’s fired.

So do we have a method in JavaScript that works in similar way as document.ready?

Partially yes.

We have a method called DOMContentLoaded  that is actually called by jQuery from document.ready. But that’s not it.  DOMContentLoaded is not available to every browser and versions. For IE > 9,  onreadystatechange works in the same way. In case nothing works in browser, jQuery has a fallback and it implemented own logic to traverse the DOM and check the when the DOM got registered and fires document.ready accordingly.

So I hope you all got to know the basic difference between these two.

Cheers,
Brij

HTML5 : Set multiple audio/video files dynamically and run one by one

One of my blog Reader was working on HTML5 audio controls. He asked me a question How can he play multiple audio files one by one. And his requirement was to set the audio files dynamically. So I thought of sharing the solution here. You can customize based on your requirement.

So what I have done. I created an audio control as

 <audio id="ctrlaudio" controls="controls" runat="server">
                Your browser does not support the audio tag.
 </audio>

As you can see an Audio control and made it as runat server, So that I can set some values from code behind. I have also created a hidden variable to set the comma separated name of songs that I want to run one by one. In my code behind I am setting a source for this audio control. My code behind as

string innerHTML =
            "<source src='song1.mp3'></source>";
        ctrlaudio.InnerHtml = innerHTML;
        hdnSongNames.Value = "song1.mp3" + "," + "song2.mp3";

So the whole logic is written in JavaScript and I have used jQuery as well. The logic is something like, First get the list of song names using hidden variable that I require to run one by one . Then I attached an event ended to the audio control. This event is fired when the current playing song is ended. And when one song ended and other next song starts playing. Let’s see the code

 $(function () {
            //Find the audio control on the page
            var audio = document.getElementById('ctrlaudio');
            //songNames holds the comma separated name of songs
            var songNames = document.getElementById('hdnSongNames').value;
            var lstsongNames = songNames.split(',');
            var curPlaying = 0;
            // Attaches an event ended and it gets fired when current playing song get ended
            audio.addEventListener('ended', function() {
                var urls = audio.getElementsByTagName('source');
                // Checks whether last song is already run
                if (urls[0].src.indexOf(lstsongNames[lstsongNames.length - 1]) == -1) {
                    //replaces the src of audio song to the next song from the list
                    urls[0].src = urls[0].src.replace(lstsongNames[curPlaying], lstsongNames[++curPlaying]);
                    //Loads the audio song
                    audio.load();
                    //Plays the audio song
                    audio.play();
                    }
            });
        });

As I have made a comment on most lines of the code, I don’t need to explain it again here. One point, I want to make it here that I have done some coding at Code behind you can totally do at Client side only. If you need any details from server, can initiate a Ajax call get the details (here list of songs) .

Also, the video tag also works similar to audio tag. So you can work similarly with video tag also.

So you can use your business logic.

[Update] Some of my blog reader asked about hdnSongNames. Let me make it bit more clear.

In second paragraph I have written “I have also created a hidden variable to set the comma separated name of songs that I want to run one by one.” So this bold hidden variable is hdnSongNames and I used an asp.net hidden field with Id hdnSongNames (The aspx part is not shown in the post). This field, I have used to access some server side values at client side. If you see in my second code snippet (which is a server side C# code), I have assigned some song names at code behind and used the same field in my third code JS code snippet to read the song names. Hope it clarifies.
Hope you all have enjoyed this.

Cheers,
Brij

Accessing other domain web services via jQuery Ajax (CORS)

Now a days, most of the web developers are working on mainly Client side programming to make the web more responsive, intuitive and user friendly. So avoiding the code behind, accessing the server via Ajax, passing and getting the data in JSON format, generating the DOM elements at Client side etc becoming very common these days and these all prepared the ground for many Client side libraries to come up and that’s what we are seeing now a days.

One of the most popular Client side library, jQuery, provides a lot of wrapper methods for writing quick and easy Client side code. You guys must have used jQuery ajax to initiate a ajax call and passing data to and fro in JSON format. As you must be knowing that XMLHTTPRequest  is the base for all Client side ajax call. All the Client side libraries provides a wrapper over it for making any AJAX call. So I’ll start with an example

I have created an empty web application and added a web page . I also added a jQuery script file. I created one small web method GetRatingValues at code behind that returns a list of numbers (Gave a name called rating). So let’s see the code and get it running

So my aspx code is like

<form id="form1">
<div><input onclick="GetRatingData()" type="button" value="GetRatings" />
<div id="ratingDetails" style="display: none;">
<h1>Available Rating Values</h1>
<div id="ratingValues"></div>
</div>
</div>
</form>

And my javascript code is like

<script type="text/javascript" language="javascript">// <![CDATA[
        function GetRatingData() {
            GetRatingValues();
        }
        function AjaxSucceeded(result) {
            $("#ratingDetails").show();
            $("#ratingValues").html(result.d);
        }
        function AjaxFailed(result) {
            alert('Failed to load');
        }

        function GetRatingValues() {
            $.ajax({
                type: "Post",
                url: "First.aspx/GetRatingValues",
                contentType: "application/json; charset=utf-8",
                data: '',
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });
        }

// ]]></script>

And my web method at code behind is as

 [WebMethod()]
    public static string GetRatingValues()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        IList ratingList = new List() { "5", "4", "3", "2", "1" };
        string str = ser.Serialize(ratingList);
        return str;
    }

Now if you run the code and Click on the button. It’ll run perfectly fine and page will be displayed as

SamedomainAjaxCall

Now let’s have another scenario. I have added a simple HTML page (Test.html) in my solution and I have added the following script on my aspx page

 function GetHTML() {
            $.ajax({
                type: "GET",
                url: "Test.html",
                success: ShowHTML,
                error: AjaxFailed
            });
        }
        function ShowHTML(data) { alert(data); }
        function AjaxFailed(result) {
            alert('Failed to load');
        }

Now if you run this code. It’ll display the html content of the page. I ran it and it displayed as expected

GetAjaxHTML

Let’s also see the HTTP Headers that I have taken via firebug

HTTP Headers

GetRequest1

Also let’s see the response of the URL

Response

If you see the encircled area in both the above picture they are pointing to localhost.

If you see the URL in both AJAX call they are pointing to same domain. But have you ever tried to initiate an jQuery AJAX call to some other domain .

What I have done here, I am running my application from IIS and I added a domain for Testing (localtest.me) in IIS. So I changed the URL in my AJAX call as

OtherDomainNewBut now if you try to run this code, it would not run. Because now the URL targeting to other domain. Let’s see again the HTTP Headers and response.

GetRequestOther

Let’s see the Response

GetResponseOtherDomainNow if you see here in the above picture the encircled area, both are different and pointing to different domain and didn’t get any result.

But why?

As I already described that every AJAX request is built on XMLHTTPRequest object and XMLHTTPRequest has some security limitation. It follows same-origin policy, it means that any HTTP request using XMLHTTPRequest initiated by a web application, can be processed only if it loaded from same domain/origin. If it requests to any other domain it will not be successful.

But as now we make lots AJAX call and some times to third party web services, it becomes hurdle to our development. To overcome this issue W3C has come up with feature called Cross-Origin Resource Sharing (CORS) which enables cross site data transfer without compromising security. To use this , we require to add few new HTTP headers that allows to add set of other origins/domains and the content type that is required to transfer.

Also let’s understand what is meant by other domain/origin?

If I have a domains like mydomain.com and mydoman1.com so as it is clear from seeing that these are different domain. Similarly subdomains like abc.mydomain.com and xyz.mydomain.com are also considered as from different origin/domain. Also at certain times the url also contains port number so if the port number is different, it also be treated as from different origin.

So as a thumb rule, you can say if the portion of URL before first single slash is different, it would be considered as from different origin and same origin policy would not be applied.

So now, let’s again back to our example. To run our example, we need to add these custom headers.  ASP.NET provides a way to add these new headers by adding some config entry. so I added the following in my web.config

GetConfig

Now if we run the code it runs successfully. Let’s analyse again the HTTP Headers and Response.

GetrequestOtherSuccess

And the Response

GetresponseOtherSuccess

Now if you see the dark encircled area, they are pointing to different domain and yet got the response. But the successful result caused by the thin encircled area in header pic, which is a new header got added. And we made this entry in web.config

But what would happen if I change the URL that I used in my first sample as

 function GetRatingValues() {
            $.ajax({
                type: "Post",
                url: "http://localtest.me/TestCORS/First.aspx/GetRatingValues",
                contentType: "application/json; charset=utf-8",
                data: '',
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });
        }

And if you run it again, It would not run. because in my last example, I was using Get Request. For Post (type: “Post”)request I can  transfer some data back and forth to server. So here I need to define one more entry in web.config that will add another header in the request as

Postheader ConfigNow after adding it, if you run the code then it’ll run like a charm.

One more point, I’ll make a here that providing * for Access-Control-Allow-Origin is not a good Idea, because it allows to access any other domain URL so it’s if you specify the particular domains here.

Hope you all have enjoyed this post. Do share your feedback.

Thanks,
Brij

Playing with List Controls using jQuery

You all must be knowing, I am fan of jQuery. The kind of neat and clean code and the power provided by jQuery at Client side scripting is unmatchable.

List Controls are one of the most used form controls. And we all know that manipulating these controls from JavaScript always have been a tough task.

In this post I’ll be discussing about accessing List controls and manipulating it with the help of jQuery. Hope you all like it and also will able to apply with other controls as well.

Continue reading

Error While Serailize/De-Serailize DateTime in JSON format : A Solution

Sometimes back, I was working on one my modules in my application. Here I had an of a Class which has some properties of DateTime type. Actually I was serializing the object using JavaScriptSerializer to serialize it in JSON format but later could not be able to deserialize it again.

So I thought of digging deep to this problem. So  I will be discussing it with an example. Let’s have a class Continue reading…

Call HTTPhandler from jQuery, Pass data and retrieve in JSON format

Download sample for here

Last few days ago, I was woking with HTTP handler. Here I was required to call handler from Client script. Later I found, that I need to pass some data to handler and also recieve some from it.

So I was looking for if there is some way we can pass some data to handler in some format and can recieve.

So Here I am going to share, How we can call a HTTPHandler from jQuery and can pass some data to handler and receive as well.

So Let’s go step by step Continue reading…

Globalisation with jQuery

Download Sample application

Introduction

Recently, Microsoft announced three jQuery plugins as Official plugin.

  • jQuery Client Templating
  • Data linking
  • Globalization

I found all of them very cool feature for web development.
I have already written articles about the first two. Please find the link below.

I think, you all must have found the above articles very useful and will be using in near future or some of you might have started using this. I would request you all that to share your views about the article, which will be very helpful for me in better writing.

Now, In this article, I am going to discuss the last feature that is Globalization. When we say Globalization, the thing that comes in our mind is resource files. ASP.NET itself provides very good facility to cater the needs of Globalization.But which requires a postback, so it doesn’t look nice and not good in performance as well.

jQuery also provides us a way to implement the globalization, with supported plugin.

Again, I am writing few common points that I wrote in my last two Articles, for the new readers.

What is Globalization

As per MSDN “Globalization is the process of designing and developing
applications that function for multiple cultures
.”

So Globalization allows us to develop an application, which provides the option to localize the application in different cultures/languages. Now as we are working in global environment and serving the entire world, it becomes the necessity, to provide the globalization feature to our application.

So in this article, I am going to discuss, How we can provide the Globalization feature with the help of jQuery.

Prerequisite

  • jQuery library
  • Plugin for Globalization

jQuery already comes with VS2008/2010. But if you are working VS 2005 then you can download from the following link.

Download jQuery

To download plugin for Globalization,
click here

Globalization with jQuery:

So in this article, I am going to discuss, How we can utilise the Globalization feature of jQuery.

jQuery provides us the power to format and parse date, number and currencies in different cultures.  jQuery plugin defines over 350 cultures that currently supported by the plugin.

There are languages those are common in few regions/countries, but the formatting of numbers, currencies and date varies. Like English is spoken in several countries USA, UK and other various European countries. For these we have several cultures defined, that is used to identify the uniqueness amongst these countries.

This plugin comes in two flavors.

One file jQuery.glob.all.js includes around 350 cultures currently. So with this we need to include only this file for all
the cultures supported by the plugin. Another way,Plugin has also culture specific js files, that can included based on cultures that are supported by the application.

Some common APIs of the Plugin:

jQuery.culture:This holds the culture information that is currently set and is used in default case, i e while formatting various values this culture is used if no culture is specified.

jQuery.preferCulture:This method is used set the culture that user prefers and this culture is used for all the formatting, parsing etc done on the page. Actually as the method name suggests, it selects the best match culture that’s JavaScript is included in the page.

jQuery.format:
This method is used to format the date, number and currency in the given format string. This method is widely used.

jQuery.findClosestCulture:
This method works in similar way as preferCulture but it returns the best matching culture and don’t set the jQuery.culture to it.

jQuery.localize:
This method allows us to extend the specific culture and returns or set
the localized value.

There are many more functions like jQuery.parseInt, jQuery.parseFloat, jQuery.parseDate etc provided by the plugin, that can be used for several specific purposes.I have discussed some of them.

Let’s see some Examples:

Here In this section, I’ll be showing you some examples.

First Example:: In this example, I am displaying the stock deatils of Infosys on a specific date. It includes the price and number of unit sold on a specific date in two different cultures. Let’s see the running application.

 

 

 

 

 

 

 

 

 

Now lets move to the code. First let’s see the aspx code

<table style="border:1px solid black; font-family:Verdana; font-size:small">
            <tr>
                <td colspan="2"><h3>English - US</h3></td>
            </tr>
            <tr>
                <td>Stock Name</td>
                <td><span id="Text1" >Infosys</span></td>
            </tr>
            <tr>
                <td>Stock Price </td>
                <td><span id="price"/></td>
            </tr>
            <tr>
                <td>Day</td>
                <td><span id="date"/></td>
            </tr>
            <tr>
                <td>Units Transacted</td>
                <td><span id="unitsTransacted" /></td>
            </tr>
            <tr>
                <td colspan="2"><h3>France - French </h3></td>
            </tr>
            <tr>
                <td>Stock Name</td>
                <td><span id="Span1">Infosys</span></td>
            </tr>
            <tr>
                <td>Stock Price </td>
                <td><span id="price1"/></td>
            </tr>
            <tr>
                <td>Date</td>
                <td><span id="date1"/></td>
            </tr>
            <tr>
                <td>Units Transacted</td>
                <td><span id="unitsTransacted1" /></td>
            </tr>
        </table>

Above as you can see, I am displaying Stock details Infosys in two different cultures English-US and France-French.
Now lets jump to script. Here the script that I have include. These are

 <script src="scripts/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="scripts/jquery.glob.js" type="text/javascript"></script>
    <script src="scripts/globinfo/jQuery.glob.all.js" type="text/javascript"></script>

So I have included three files here. First the jQuery file the common Global file and last one is the file that contains all culture specific details.
Now rest javascript code is

       // Set culture
        jQuery.preferCulture("en-US");

        // Formatting price
        var price = jQuery.format(3899.888, "c");
        //Assigning stock price to the control
        jQuery("#price").html(price);

        // Formatting date
        var date = jQuery.format(new Date(2010, 11, 15), "D");
        //Assigning date to the control
        jQuery("#date").html(date);

        // Formatring units trabsacted
        var units = jQuery.format(45678.576, "n2");
        //Assigning units to the control
        jQuery("#unitsTransacted").html(units);

        // Set culture
        jQuery.preferCulture("fr-FR");

        // Format price
        var price = jQuery.format(3899.888, "c");
        //Assigning stock price to the control
       jQuery("#price1").html(price);

        // Format date available
        var date = jQuery.format(new Date(2010, 11, 15), "D");
        //Assigning date to the control
        jQuery("#date1").html(date);

        // Format units in stock
        var units = jQuery.format(45678.576, "n2");
        //Assigning units to the control
        jQuery("#unitsTransacted1").html(units);

As you can see from the above code, that I have used the preferCulture method to set the culture and format method to format the various data like price, date and units here.

So above one is the simple example which describes that how the plugin works.

Changing culture dynamically:

Now in this example, I am talking about another scenario where user may want to select the culture dynamically, and want to get the page updated accordingly.

In my sample example, I am having one dropdown, user selects the culture and page is getting updated accordingly.
First lets see the application.

 

 

 

 

 

 

 

 

Now let’s jump on the code.First let’s view the aspx code

 <table style="border:1px solid black; font-family:Verdana; font-size:small">
            <tr>
                <td style="font-weight:bold">Select Culture</td>
                <td>
                    <select id="ddlCultures">
                        <option value="en-US">English - US</option>
                        <option value="en-IN">EngLish - India</option>
                        <option value="en-AU">EngLish - Australia</option>
                        <option value="fr-FR">French - France</option>
                        <option value="es-MX">Spanish - Mexico</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td style="font-weight:bold">Stock Name</td>
                <td> <span id="Text1">Infosys </span></td>
            </tr>
            <tr>
                <td style="font-weight:bold">Stock Price</td>
                <td><span id="price"/></td>
            </tr>
            <tr>
                <td style="font-weight:bold">Day</td>
                <td><span id="date"/></td>
            </tr>
            <tr>
                <td style="font-weight:bold">Units Transacted</td>
                <td><span id="unitsTransacted"/></td>
            </tr>
        </table>

Now let’s see the scripts included

<script src="scripts/jquery-1.4.2.js" type="text/javascript"></script>
<script src="scripts/jquery.glob.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.en-US.min.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.en-IN.min.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.en-AU.min.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.fr-FR.min.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.es-MX.min.js" type="text/javascript"></script>

As you can see above,I have included culture specific files instead of one common files for all the cultures. Because the size of common files for all 350 cultures could be a performance overhead. As we know, that these are specific
cultures that are going to be used in the application, then we should go for culture specific files.

Now javascript code

     LoadPage("en-US");

     jQuery("#ddlCultures").change(function() {
         var selectedCulture = this.value;
         LoadPage(selectedCulture);
     });

        function LoadPage(selectedCulture) {

            jQuery.preferCulture(selectedCulture);

            var price = $.format(3899.888, "c");
            jQuery("#price").html('12345');

            // Format date available
            var date = $.format(new Date(2011, 12, 25), "D");
            jQuery("#date").html(date);

            // Format units in stock
            var units = $.format(45678, "n0");
            jQuery("#unitsTransacted").html(units);
        }

In this code, I have taken a dropdown with multiple cultures. One can select the desired culture and page will be modified accordingly. I have used the same form but I have called preferculture method based on the selection of dropdown.

Rest code is same as above example.

Picking culture info from Browser:

Sometimes user also set culture preferences in the browser. And lots of applications rely on it. So we can also read the culture information from the browser and can load the page accordingly. To get the culture information we
can use the following.

  var language = "<%= Request.UserLanguages[0] %>";
  jQuery.preferCulture(language);

Conclusion:

This feature is very useful for the applications targeting the entire Globe. As you are moving forward for RIA applications, this plugin of jQuery could be key.

Hope you all must have enjoyed my above article. Please share your valuable feedback, that will help me a lot for better writing.

Feedback and Suggestions:

Hope you all must have enjoyed my above article. Please share your valuable feedback, that will help me a lot for better writing.

Data linking with jQuery

Download Sample

Recently, Microsoft anounced three jQuery plugins as Official plugin.

  • jQuery Client Templating
  • Data linking
  • Globalisation.

In my last article, I discussed about the jQuery Templating. You can view that Article here .

So I think, you all must find Templating article very useful. Because, by the time
web applications development is evolving, we are moving towards Client side
development/scripting, to provide fast and very trendy/flashy look and feel.

So in this article, I am going to discuss another very cool feature, ie
Data linking.This helps us linkling the data and the UI.

What is jQuery:

jQuery is a JavaScript library that works on top of the JavaScript.
jQuery provides a very simple way for HTML document traversing,
DOM manipulation, event handling, animating, and Ajax interactions for
rapid web development. That could have been very complex while working
with normal JavaScript.

jQuery is becoming more and more popular day by day. Even it was integrated
with VS2008 and also available with VS2010.
jQuery is open source. Due to its features,
Microsoft started to support jQuery team and also working with them,
to provide better web based tools to their Clients.

Prerequisite:

  • jQuery library
  • A plugin for datalinking
  • JSON library

jQuery already comes with VS2008/2010. But if you are working VS 2005 then you can
download from the following link.

Download jQuery

To download JSON library,
click here

Data Linking:

Data kinking provides us a way, to link our data/objects to UI controls.
Means, if the controls get updated, the underlying data object would
also be updated. In the same way, if the data objects get updated,
the controls on UI will also get updated (In case of two way linking).

Means once you linked your data with the controls, you don’t need think about
the data object. The syncing between data object and your UI will be taken care
by the jQuery plug in.

So you can imagine, you dont need to get the updated data from the
controls and update the object, which is required at the time
of saving the data at server. Which requires lot more code to be
written and also error prone.

There are several options to link the data.

  • One way Linking
  • Two way Linking

One Way Linking:

One can link the UI controls to some object. Means the object will
always be in sync with UI. Whenever the Data in UI will get changed the underlying
object will also get updated. So one need not worry about the data once it is
done, one can send the object directly to the server for further processing

I have explained it with one sample.

In my example, there is form named as Add Vehicle, where user can enter the
Vehicle name and its price, then click on the Add Vehicle to add the vehicle
at server side.
One can also see the state of the underlying object at any point of time, using
Show Updated Object button.
Now lets go through the code.

Lets see aspx code first

 <table>
            <tr>
                <td colspan="2"><h2>Add Vehicle to Vehicle Store</h2></td>
            </tr>
            <tr>
                <td>Vehicle Name</td>
                <td><input id="txtVName" type="text" /></td>
            </tr>
            <tr>
                <td>Price</td>
                <td><input id="txtVPrice" type="text" /></td>
            </tr>
            <tr>
                <td><input id="btnShow" type="button" value="Show updated object"
                 onclick="ShowUpdatedData();"/> </td>
                <td><input id="btnAdd" type="button" value="Add vehicle to store"
                 onclick="AddVehicle();"/> </td>
            </tr>
        </table>

Here I have two input box to enter the name and price of the vehicle, and two
buttons, one to show the object and other one to add it.

Now lets move to Javascript code,

 var vehicle = {};
 //linking the UI controls with vehicle object
        $(document).ready(function() {
        $(vehicle)
            .linkFrom('Name', '#txtVName', 'val')
            .linkFrom('Price', '#txtVPrice', 'val')
    });

Here I have a global variable vehicle that is linked with the using
linkForm method for the plugin as shown above.

I have also written the code for adding the data at server, using
jQuery Ajax Call as

 function AddVehicle() {
        var inputs = new Object();
        inputs.vehicle = JSON.stringify(vehicle);
        $.ajax({
            type: "POST",
            url: "AddVehcle.aspx/AdVehicle",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: ShowStatus,
            error: AjaxFailed
        });

    }
    function ShowStatus(result) {
        alert(result.d);
    }
    function AjaxFailed(result) {
        alert('Ajax failed');
    }

    //to show the state of the object
     function ShowUpdatedData() {
        alert([vehicle.Name, vehicle.Price]);
    }
    

Also lets have a look at server side code


public partial class AddVehicle : System.Web.UI.Page
{
public static List lstVehicle = null;
protected void Page_Load(object sender, EventArgs e)
{

}
//This method adds one vehicle
[WebMethod()]
public static string AdVehicle(string vehicle)
{
if (lstVehicle == null)
{
lstVehicle = new List();
}
JavaScriptSerializer ser = new JavaScriptSerializer();
Vehicle objVehicle = ser.Deserialize(vehicle);
lstVehicle.Add(objVehicle);
return "Vehicle added sucessfully";
}
}

public class Vehicle
{
public string Name { get; set; }
public decimal Price { get; set; }
}

The above code is self-explanatory.AdVehicle() is called to add a vehicle using Ajax call.

Now lets run the application,
Here I have entered data about one vehicle,

Now when I click to see the updated object, ShowUpdatedData
then get to see the vehicle object as below

Converters:

There is also a good feature provided. We may not
want to save the data as we show at UI. Like if there is some price or quantity,
we may want to format the quantity in some manner before saving. So for that
we can put some converters at the time of linking as

 $(document).ready(function() {
    $(vehicle)
        .linkFrom('Name', '#txtVName', 'val')
        .linkFrom('Price', '#txtVPrice', 'val',
        //Converter that will be called before updating the underlying object
        function(value) { return value.replace(/[^0-9.]/g, "") }
        );
     });

As you can see, I have a converter with Price, that will return only numbers and dot.
Lets see it running

What it is doing, its taking the value from the textbox converting it with the
conerter and the setting to property Price of the vehicle object.

Two way linking:

It also do all the things as above but have one more feature. You can also update the object from code also,  as soon as object will get updated that will also be reflected in the UI.

This feature can be very use full in editing/searching feature.You searched
some data and now want to update it. Now you can update UI as well as underlying
object, both UI and data will always be in sync.

I have discussed it with one sample

In my example, Lets we have a list of person at server. One can fetch the
details of an existing person.One also update the existing person or can add a
new person.

So I have created one class person as

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string SSN { get; set; }
    public string Gender { get; set; }
    public string ContactNo { get; set; }

}

My aspx page is as

<table>
            <tr>
                <td> Name </td>
                <td>
                    <input id="txtPersonName" type="text" />
                    <input id="Button1" type="button" value="GetPersonDetails"
                    onclick="PopulatePersonDetails();"/>
                </td>
            </tr>
            <tr>
                <td colspan="3"> <b>Person Details</b></td>
            </tr>
            <tr>
                <td>Name</td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td>Age</td>
                <td><input id="txtAge" type="text" /></td>
            </tr>
            <tr>
                <td>SSN</td>
                <td><input id="txtSSN" type="text" /></td>
            </tr>
            <tr>
                <td>Gender</td>
                <td><input id="txtGender" type="text" /></td>
            </tr>
            <tr>
                <td>Contact Number</td>
                <td><input id="txtCNo" type="text" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input id="Button3" type="button" value="Show Updated JS Object"
                     onclick="ShowUpdatedData();"/>
                    <input id="Button2" type="button" value="Add/Update Person"
                     onclick="UpdateorAddData();"/>
                </td>
            </tr>
        </table>

As you can see, in my page I have put the input boxes for every property of
person.

At the start of the page I have also, provided a input box to enter the person name and
a button to fetch the requested person from the server.

I have provided two more buttons, One to see the updated objects in javascript alert
and another one to update the data at the server. It actually looks the list for the SSN if it found then update the existing record else add the new
person. We’ll see the code in a moment.

Now lets move the Javascript code that is written.
The code that is used to link the data

First I have declared one global object that object will be linked to the UI controls
as
var person = {};

and the code for linking the data is

//Linking the controls from the object
 $(document).ready(function()
    {
        $(person)
        .linkBoth('Name','#txtName','val')
        .linkBoth('Age','#txtAge','val')
        .linkBoth('SSN','#txtSSN','val')
        .linkBoth('Gender','#txtGender','val')
        .linkBoth('ContactNo','#txtCNo','val');

    });

As from the above you can see, that person object is used and
linked using linkBoth method, which takes three parameters
first the name of the property of the object,
second the id of the control with sign #
third val
Now, after this you don’t need to worry about the data, all things will be taken care the
plugin itself.

Rest javascript method, I have used

// To fetch the detail from the server of the entert person name
 function PopulatePersonDetails() {

        var inputs = new Object();
        inputs.name = document.getElementById('txtPersonName').value;

        $.ajax({
            type: "POST",
            url: "EditPerson.aspx/GetPerson",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: AjaxSucceeded,
            error: AjaxFailed
        });

        // To be called when ajax call succeeded
        //If no object will be found, it'll show an error message as
        //'Person Not found' else call update the person object
         function AjaxSucceeded(result) {
            if (result.d == 'null')
                alert('Person Not found');
            else
                $(person).attr(JSON.parse(result.d));
        }

        //Will be called, if ajax call gets failed somehow.
        function AjaxFailed(result) {
            alert('Ajax failed');
        }
    }

For the functionality of the updating or adding the person
object at server we have following methods

    //This function get the global variable person object
    //which is always sync with with UI and sends it
    //to server to add/update
    function UpdateorAddData() {

        var inputs = new Object();
        inputs.person = JSON.stringify(person);
        $.ajax({
            type: "POST",
            url: "EditPerson.aspx/AddUpdatePerson",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: ShowStatus,
            error: AjaxFailed
        });

        }

        //This function is to show the status whether a new person is added or updated
         function ShowStatus(result) {
            alert(result.d);
        }

As I have linked the object to the UI controls, so I am just picking or updating
the person object, that always gives the most updated and synced data.

Also lets have a look to server side code

public partial class EditPerson : System.Web.UI.Page
{
public static List lstPerson = null;
protected void Page_Load(object sender, EventArgs e)
{
}

//This method will return the searched person.
[WebMethod()]
public static string GetPerson(string name)
{
InitializePersons();
JavaScriptSerializer ser = new JavaScriptSerializer();
// ser.Serialize(persons);
return ser.Serialize(lstPerson.Find(p => p.Name == name));
}

//This method will add or update a person based on SSN
[WebMethod()]
public static string AddUpdatePerson(string person)
{
string status;
JavaScriptSerializer ser = new JavaScriptSerializer();
Person obj = ser.Deserialize(person);
InitializePersons();
Person per = lstPerson.Find(p => p.SSN == obj.SSN);
if (per == null)
{
lstPerson.Add(obj);
status = "New person added";
}
else
{
// Updating the person
lstPerson.Remove(per);
lstPerson.Add(obj);
status = "Person updated";
}

// ser.Serialize(persons);
return status;
}

public static void InitializePersons()
{
if (lstPerson == null)
{
lstPerson = new List()
{
new Person { Age = 27, Name= "Brij",
Gender="Male", ContactNo="123456789",
SSN="CC123456"},
new Person { Age = 18, Name = "Ravi",
Gender = "Male", ContactNo = "987654321",
SSN="AB654321"}
};
}
}
}

Lets see the runing application,

I have few person data at server.When I am entering and clicking
for getting the person details, UI gets updated. While actually I am making
an Ajax call, to get the person data and updating the underlying object
as discussed in above code.

Rest things as per the Vehicle Store example

I have also to added a button, which one can click to see the state of the person
object at any point of time, when one wants.

Please find the full sample in attachment

Conclusion:

I found this feature very useful, while using ajax and jQuery
as I discussed in above example. One should go for the one way or two way linking
based on their requirements.

Hope you all must have enjoyed my above article. Please share your valuable
feedback, that will help me a lot for better writing.

Feedback and Suggestions:

Hope you all must have enjoyed my above article. Please share your valuable
feedback, that will help me a lot for better writing.

Also lets have a look at server side code

Client Templating with jQuery

jQuery templating is becoming a new buzzword for the new Web applications. One cannot avoid jQuery in web applications. Currently most of the applications are using jQuery heavily. It provides very good look & feel and better performance.

There are a lot of plugins are also available for jQuery, they provides really cool feature. We can provide a very new and trendy look and feel with the help of jQuery. Also, as we are making very rich application, performance is also becoming a key point for our applications. jQuery helps a lot in this regard also. We will be discussing mainly jQuery Templating in this article

What is jQuery:

jQuery is a JavaScript library that works on top of the JavaScript. jQuery provides a very simple way for HTML document traversing, DOM manipulation, event handling, animating, and Ajax interactions for rapid web development. That could have been very complex while working with normal JavaScript.

jQuery is becoming more and more popular day by day. Even it was integrated with VS2008 and also available with VS2010. jQuery is open source. Due to its features, Microsoft started to support jQuery team and also working with them, to provide better web based tools to their Clients.

Prerequisite:

  • jQuery library
  • A plugin for templating
  • JSON library

jQuery already comes with VS2008/2010. But if you are working VS 2005 then you can download from the following link.

Download jQuery

To download plugin for templating feature, click here
Relax guys!! you won’t need this plugin after jQuery 1.5. This would integrated with the main library itself Smile

To download JSON library, click here

jQuery Templating:

As we are working on Client server architecture, most of the things are done by the server itself. Server sends the HTML response to the Browser and browser just display it. Earlier, we were not doing lot of things at client side, Normally, some validation and little bit more at client side. With the help of Ajax call from Client side and retrieving data in a very convenient format in JSON, it really becomes easy, to start moving server side code to Client side. Means the data travelling from server to Client, is not the whole HTML response but it is just data that we have to show in different HTML controls.

Lets see an pictorial overview

jQuery and Ajax

Templates :

To use the client templating. You need the following

  • First, data at client side
  • Client side template
  • Now with the help of jQuery, make the HTML elements and adding it to the DOM. Now I am explaining one example. In my example, I am displaying list of Persons. And also adding a person later.Displaying Data:So here, first I am showing the details of Persons. The data is coming in JSON format with the help of Ajax call, in document.ready function.Lets move step by step:I have created a Client template to display the person data.The template is:
<br />
 <script type="text/html" id="personTemplate">
<div>
<div style="float:left;"> ID : </div>
<div>${UId} </div>
<div style="float:left;"> Name : </div>
<div>${Name} </div>
<div style="float:left;"> Address : </div>
<div>${Address} </div>

       </div>

   </script></p>
<p>

But, why have I put it in script tag? Because we don’t want to render it. We will
be using this as a template for displaying the data. Also see, I have made the
type as text/html.

Here, in the template, ${UId}, ${Name} and ${Address}
are replaced by the actual values from the data provided. The name of the properties in provided class is same.

At server side, I made a WebMethod that will be called from the
client to fetch all the person data. As

My Person class is as

<br />
public class Person<br />
{<br />
    public int UId { get; set; }<br />
    public string Name { get; set; }<br />
    public string Address { get; set; }<br />
}<br />

My WebMethod is as

<br />
[WebMethod()]<br />
public static string GetPersons()<br />
{<br />
    List persons = new List()<br />
    {<br />
        new Person { UId = 1, Name = "Brij", Address = "Noida"},<br />
        new Person { UId = 2, Name = "Rahul", Address = "New Delhi" },<br />
        new Person { UId = 3, Name = "John0", Address = "Chris"}<br />
    };</p>
<p>    JavaScriptSerializer ser = new JavaScriptSerializer();<br />
    return ser.Serialize(persons);</p>
<p>}<br />

I created the static data in the code, one can fetch from where s/he wants,
either some database or some file or some other datasource.

Here I have used the namespace System.Web.Script.Serialization
for JavaScript serialization.

I have made a Ajax call at document.ready to get all the persons data.And ,
displayed the data on UI.

//It gets called as soon as Dom gets loaded

<br />
 $(document).ready(function() {<br />
           PopulatePersons();<br />
       });</p>
<p> //Creating the ajax call, and if succeeded then display the result on UI<br />
 function PopulatePersons() {<br />
     $.ajax({<br />
         type: "POST",<br />
         url: "Default.aspx/GetPersons",<br />
         contentType: "application/json; charset=utf-8",<br />
         data: "{}",<br />
         dataType: "json",<br />
         success: AjaxSucceeded,<br />
         error: AjaxFailed<br />
     });</p>
<p>        }<br />
        function AjaxSucceeded(result) {<br />
            Display(result);<br />
        }<br />
        function AjaxFailed(result) {<br />
            alert('no success');<br />
        }</p>
<p>

After fetching the data, from the server, we are rendering the data using jquery
templatng feature

<br />
function Display(result) {</p>
<p>            var persons = eval(result.d);<br />
            personCount = persons.length;<br />
                $("#personTemplate").tmpl(persons).appendTo($("#divPerson"));<br />
        }<br />

Here , what I am doing,I am parsing the data that is returned by webservice.
After that, I am passing it to the tmpl function.
This line of code

$("#personTemplate").tmpl(persons).appendTo($("#divPerson"));

means use the template personTemplate for rendering the
persons data and add it to the container div divPerson

Adding/Updating Data:

For adding more person on UI, I have added a HTML button on my page, to add a person. As

<br />
<input id="Button1" type="button" value="AddMorePerson"        onclick="AddPerson();"/><br />

Onclick of Add button, I am fetching the data from server using Ajax call.

<br />
function AddPerson() {</p>
<p>            var inputs = new Object();<br />
            inputs.count = personCount;</p>
<p>            $.ajax({<br />
                type: "POST",<br />
                url: "Template.aspx/AddPerson",<br />
                contentType: "application/json; charset=utf-8",<br />
                data: JSON.stringify(inputs),<br />
                dataType: "json",<br />
                success: AjaxSucceeded,<br />
                error: AjaxFailed<br />
            });</p>
<p>        }<br />

After fetching the data, display it with the help of client templating., As

<br />
 function DisplayChildren(result) {</p>
<p>            var persons = eval(result.d);<br />
            personCount = persons.length;<br />
                $("#personTemplate").tmpl(persons).appendTo($("#divPerson"));<br />
        }<br />

It just append the a person detail in the existing div as above.

Note: One should keep in sync the name of the properties
of the class and used in template one.

Nested Templates also works same as above but here we’ll be using one template
in the other.This type of requirement is very common, when we need to show
the details of any item one to many or many to many mapping.

So here, I have discussed it with a sample example.

Here i have an employee class which has a list of address, Means an employee can
belong to multiple addresses. My employee and address class are like

<br />
public class Address<br />
{<br />
    public string Street { get; set; }<br />
    public String AddressLine1 { get; set; }<br />
    public String AddressLine2 { get; set; }<br />
    public string City { get; set; }<br />
    public string Zip { get; set; }<br />
}<br />
 

and Employee class

<br />
public class Employee<br />
{</p>
<p>    public int EmployeeId { get; set; }<br />
    public String Name { get; set; }<br />
    public int Age { get; set; }<br />
    public List Addresses { get; set; } }<br />

now the webmethod that is returning the data

[WebMethod()]
    public static string GetEmployees()
    {
        List persons = new List()
        {
            new Employee { EmployeeId = 1000, Age=34, Name ="Rahul",
                Addresses = new List()},
            new Employee { EmployeeId = 1001, Age=29, Name ="Atul",
                Addresses = new List()},
            new Employee { EmployeeId = 1002, Age=32, Name ="Rohan",
                Addresses = new List()}

        };
        persons[0].Addresses.Add(new Address() { Street = "Street 5", AddressLine1 = "New Bay Area", AddressLine2 = "Near Roma Hospital", City = "Kolkata", Zip = "221001" });
        persons[0].Addresses.Add(new Address() { Street = "Bahadur marg", AddressLine1 = "Kailash Colony", AddressLine2 = "Near Public School", City = "Lucknow", Zip = "226001" });
        persons[0].Addresses.Add(new Address() { Street = "Ali Crossing", AddressLine1 = "Republic Colony", AddressLine2 = "Silk Garden", City = "Ahamedabad", Zip = "221021" });

        persons[1].Addresses.Add(new Address() { Street = "Street No 2", AddressLine1 = "Pocket Gama", AddressLine2 = "Near Appollo Hospital", City = "G Noida", Zip = "201301" });
        persons[1].Addresses.Add(new Address() { Street = "1634", AddressLine1 = "Sector 15", AddressLine2 = "Near Nirulas", City = "Noida", Zip = "201301" });

        persons[2].Addresses.Add(new Address() { Street = "Street 10", AddressLine1 = "Sector 18", AddressLine2 = "Near Mosaic", City = "Noida", Zip = "201301" });
        persons[2].Addresses.Add(new Address() { Street = "Gol Marg", AddressLine1 = "New Era Colony", AddressLine2 = "Pitambaram", City = "Alllahabad", Zip = "221001" });

        JavaScriptSerializer ser = new JavaScriptSerializer();
        return ser.Serialize(persons);
    }
}

Now as above at client side, this data is displayed using templating feature.

Now at client side, My client side templates woulld be

Parent Template:

<br />
<script type="text/html" id="empTemplate">
<div>
<div style="float:left;font-weight:bold;"> ID : </div>
<div>${EmployeeId} </div>
<div style="float:left;font-weight:bold;"> Name : </div>
<div>${Name} </div>
<div style="float:left;font-weight:bold;"> Age : </div>
<div>${Age} </div>
<div style="font-weight:bold;">Addresses:</div>
<div style="margin-left:10px;">{{tmpl($data) "#AddressTemplate"}}</div>
</div>

 </script><br />

Child Template:

<br />
<script id="AddressTemplate" type="text/html">
      {{each Addresses}}
<div style="float:left;font-weight:bold;"> Street : </div>
<div>${Street} </div>
<div style="float:left;font-weight:bold;"> AddressLine1 : </div>
<div>${AddressLine1} </div>
<div style="float:left;font-weight:bold;"> AddressLine2 : </div>
<div>${AddressLine2} </div>
<div style="float:left;font-weight:bold;"> City : </div>
<div>${City} </div>
<div style="float:left;font-weight:bold;"> Zip : </div>
<div>${Zip} </div>

      {{/each}}
   </script><br />

As here you can see in child template, I have put the template in the tags
{{each Addresses}}{{/each}}. It just render the inside template for every
address. It works like foreach.

Now inside the parent template, the line code

{{tmpl($data) "#AddressTemplate"}}
indicates
it gets the data ie here list of Addresses and apply the templating on the template
AddressTemplate

Now lets run the application:

Nested Templates

Microsoft Announcements:

Around a month back, Microsoft announced three plugins as new official plugin for jQuery.
– Templating
– Datalinking
– Globalisation
New Official jQuery Plugins Provide Templating, Data Linking and Globalization

In upcoming version of jQuery ( jQuery 1.5) , we would not require to add a plugin for Templating fetaure. This will be part of jQuery 1.5.

In my this article, I discussed Templating and in my upcoming articles I will be talking about Datalinking and Globalization.

Conclusion:

As I already discussed in Introduction section, that jQuery templating provides us a very rich feature to generate the UI without writing much code and in efficient manner. So one should use templateing feature wherever possible. This feature may be very good, where we display the lot of data and also it may get updated. I used it in my application, in almost every page and found it very efficient than server side code.

Feedback and Suggestions:

Hope you all will this Article and will give your valuable feedback which will be very helpful for me to write better content next time.