Category Archives: Jquery

Converting a Json string to C# object using JavaScriptSerializer

Gradually web development is shifting it’s focus to Client side programming day by day. Json is simply a Fat Free alternative to XML. Earlier XML was our commonly accepted data format across all the platforms, but JSON seems to be even more promising because of it’s light weight and familiar syntax (reminds me of .Net  object initializer).   Jquery on the other hand has become a standard which has excellent support with JSON format.

Let’s say we have a C# class Product.


class Product {

int ProductID;

string ProductName;

int CategoryID;

int SupplierID;

decimal UnitPrice;

}

JSON string example : We need to make sure our json string syntax is correct.  Class property names should be same to map it by default.

Here is the syntax

“{Property1 : ‘stringvalue’ , Property2 : ‘stringValue2’, Property3 : 123 }”

var jsonProductString = "{ ProductID :" + pid + ", ProductName :'" + pName + "',CategoryID :" + categoryId + ", SupplierID :" + supplierId + ", UnitPrice :" + unitPrice + "}";

Conversion to C# object: this is code is tested in .Net4.0.


System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

 var p = serializer.Deserialize<Product>(args);
// p is Product object initialized with Json string values.

Interesting part is after deserialization all the data types are easily mapped to Product class data types

Update:  There is a new serialization technique which performs even better for Json serialization. It is Json.Net library developed by James Newton King. it is available on codeplex.

Read more about Json.Net library on my Post on Json.Net library.
I hope it will be useful!!

Advertisements

Jquery – Calculate number of days between two dates.

This is a very common requirement we get almost in every project that’s why It is really helpful to keep it handy.


function calculateDifference() {
var startDate = $("#start_date").val();

if (startDate == “”) {
alert(“Enter start date”);
return;
}
var endDate = $(“#end_date”).val();
if (endDate == “”) {
alert(“Enter end date”);
return;
}

var startDateSplit = startDate.split(“/”);
var endDateSplit = endDate.split(“/”);

var stDate = new Date(startDateSplit[2], startDateSplit[0] – 1, startDateSplit[1]);
var enDate = new Date(endDateSplit[2], endDateSplit[0] – 1, endDateSplit[1]);

var difference = (enDate.getTime() – stDate.getTime()) / (1000 * 60 * 60 * 24);

$(“#date_difference”).val(difference);
}

I hope it helps.

Jquery event binding – jquery live api

Hi All,

Recently i faced an issue while developing a Asp.Net MVC3.0 application. On a link click i was trying to add new html to the existing DOM. For example on click of a link i was adding some new html tags to the existent DOM. Here is the code i wrote to make an ajax call on link click.


$(".editanchor").click(function () {

$.ajax({
// set the attributes and call an action method
});
});

It all worked fine but strangely when i click the link next time nothing happens. Then i realized the mistake i made while binding the click event to a handler.

As per jquery documentation Live() method should be used to bind the event to a callback if we are modifying the DOM structure during our page reload (partial or full) so that it would retain the binding next time you click the link.

Live(event, handler) : Attaches an event handler for all elements which match the current selector, now and in the future.

so the correct way to bind an event to a handler in such condition would be

$(".editanchor").live('click', function () {

$.ajax({
// set the attributes and call an action method
});
});

There are few performance considerations we should be aware of

  • Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  • jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.

EDIT: Here is the updated comparison of various flavors of binding an event.

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

I hope it helps.