Blog Archives

Json data – Thinner and familiar data format

I have written a little about json in bits and pieces in my erlier posts but moving further i felt a strong urge to put it altogether about Json. Mainly from development perspective which should cover from basic syntax to serialization and desrialization of json data. It also consists of links to good articels wherever needed.

Json (Javascript object notation) is a data format which is a thinner and cleaner than xml/soap formats. I am putting main points here that can get you started right away. Please refer to W3Schools on Json for the detailed syntax.

  • Data is in name/value pairs
  • Data is separated by comma
  • Json values can be integer,floating point,string(in double quotes),boolean (true/false),Array (square brackets), object(curly brackets) or NULL

Mostly we deal with object oriented way of representation so let me take an example.

Employee.cs it is a c# class.


public class Employee{

public string Name {get;set;}

public int      Age    {get;set;}

public bool   IsPermanent {get; set;}

Json representation of an Employee object:


// single object of an employee

{"Name" : "praveen" , "Age" : 30, "IsPermanent" : true }

// list or array of employees. please note the square brackets.

var employeesArray = [

{ "Name" : "praveen"   , "Age" : 30 ,"IsPermanent" : true} ,

{ "Name" : "amit"      , "Age" : 27 ,"IsPermanent" : false} ,

{ "Name" : "sudhakar"  , "Age" : 27 ,"IsPermanent" : true}

]

Now that you must be comfortable with the syntax of Json data. next step is to understand how to handle Json data effectively.In this post i will discuss how to consume a webapi http service which returns an object in Json data format.

Note: To create WebApi service please refer to My Post on How to create a WebApi

Let us see few jquery methods we can use to fetch Json data.

Using $.ajax(type,uri,onSuccessMethod,onErrorMethod): .ajax() is much familiar method as it is more generic in nature and can call “Get”, “Post” etc. type of requests. you can also specify content type (default is xml).


function find() {
var id = $('#empId').val();
var httpApiUri = "api/employees/" + id;
$.ajax (
type   :  "GET",
url     :   httpApiUri ,
contentType : "json",

success  : function(data){
              $.each(data, function (index,item){
               $("#employeestable").append("<tr><td>" + item.FirstName + "</td>" + "<td>" + item.LastName + "</td>");
              });
           },
error   :  function (jqXHR, textStatus, err) {
             alert('Error: ' + err);
           });
);
}

Using $.getJSON(uri,successmethod): Unlike $.ajax() method this one is specific to “Get” type of requests and fetch the data in Json format by default which is great if you are sure of your data format beforehand.

function find() {
var id = $('#empId').val();
var httpApiUri = "api/employees/" + id;
$.getJSON ( httpApiUri , function(data){
                         $.each(data, function (index,item){
                               $("#employeestable").append("<tr><td>" + item.FirstName + "</td>" + "<td>" + item.LastName + "</td>");
                               });
                         }
          )
          .fail( function (jqXHR, textStatus, err) {
              alert('Error: ' + err);
           });
}

How to send the json data as a parameter?
Now that you know how to represent Json data using javascript notation and jquery syntax.Next step is to serialize your normal data say a javascript variable and send it as a parameter to a webapi service for instance. I am considering Jquery as an example here as it is the most widely acceptable cross browser javascript library. There are various jquery apis available to achieve this.

Using JSON.stringify( jsonData ):  Let’s say i want to make a “post” request to add an employee using an http service. you can use JSON.stringify() method which is available on Json2.js on GitHub.You need to include this js file in your code. This method will serialize your javascript variable into json format and send it over the wire.

Note: One important thing about $.ajax() method is that the parameters contentType  is a format which is returned on success of the call. data  is the parameter which defines datatype of the parameter you are sending to the service. both in this example are json.


<script type="text/javascript">

$("#btnInsert").click( function() {

var empObj ='{ "FirstName" : "Praveen"   , "LastName" : "Saxena"}' ;

$.ajax({

type: 'POST',
url: 'http://serverName:portNo/Employees/PostEmployee',
data: <strong>JSON.stringify(empObj </strong><strong>)</strong>,
contentType: 'application/json',
processData: true,
success: function (result) {
$('#results').html('Result: ' + JSON.stringify(result));
},
error: function (xhr, status, error) {
$('#results').html('Error: ' + xhr.responseText);
}
});

}
</script>


Using jQuery.ParseJSON(jsonData):
This method is added in jquery version -1.4.1 onwards so you dont need to include any other js file. It performs the similar operation.


<script type="text/javascript">

$("#btnInsert").click( function() {

var empObj ='{ "FirstName" : "Praveen"   , "LastName" : "Saxena"}' ;

$.ajax({

type: 'POST',
url: 'http://serverName:portNo/Employees/PostEmployee',
data: <strong>jQuery.parseJSON(empObj </strong><strong>)</strong>,
contentType: 'application/json',
processData: true,
success: function (result) {
$('#results').html('Result: ' + JSON.stringify(result));
},
error: function (xhr, status, error) {
$('#results').html('Error: ' + xhr.responseText);
}
});

}
</script>

Deserializing JSON data: Now that you know 1) Json syntax 2) jquery apis to send json data as parameter, we need to know how to deserialize the json data at code side. We have several ways to do it.
I found Json.net library very easy to use and i have a detailed post dedicated to JSON.Net. Please refer to  My Post on Json.Net to serialize an deserialize Json data

Now if you are given your next task on jquery with services dealing with json data, i guess you are good to go 🙂 (or at least googled code will start making sense if you are not fully prepared)

Hope it helps!

Praveen

 

Advertisements

Jquery Modal dialog as Confirm in Asp.Net webforms

I love Jquery! it made me friends with client side scripting. Earlier it used to haunt me all the time.

If we have a button on a webform which should confirm the user action on click like a Delete button Jquery provides
Javascript methods:

<script type="text/javascript">
 $(document).ready(function () {
// this method opens a div with id="dialogContent" as a modal dialog box with Yes and No buttons.

$('#dialogContent').dialog({

autoOpen: false,
modal: true,
 bgiframe: true,
 title: "Confirm your action",
 width:200,
 height: 200
 });

});

// this method is called when Delete button is clicked.
function rowAction(uniqueName) {

$('#dialogContent').dialog('option', 'buttons',
 {
 "Yes": function () {
 __doPostBack(uniqueName, '');
 $(this).dialog("close");
 },
 "No": function () { $(this).dialog("close"); }
 });

$('#dialogContent').dialog('open');

return false;
 }
 </script>

.aspx code:


<asp:Button ID="btnDelete" runat="server" CommandArgument='<%# Eval("ProductID") %>'
Text="Edit" OnClick="btnDelete_Click" OnClientClick="javascript:return rowAction(this.name);" />

<div id="dialogContent">
Are you sure?

</div>

Code behind :


protected void Page_Load(object sender, EventArgs e)
 {

// register the postback reference. specify the control we are forcing to postback.

ClientScript.GetPostBackEventReference(btnDelete, string.Empty);
 }

// this event is fired when user presses <strong>Yes</strong> from Confirm Modal dialog.

protected void btnDelete_Click(object sender, EventArgs e)
 {
Button b = sender as Button;
if (b != null)
{
// do your actions here
}
 }

This way we get Jquery modal confirm box on a button click. once you press Yes we use our old friend javascript method __doPostBack(controlName, ”) to continue server side execution.

Please note that in __doPostback method second parameter is empty string,  If you need to pass some arguments while enforcing a postback. convert it to a Json string and pass it to code behind. You can convert this json string to C# object using Javascript serializer. 
Please refer to my article on json string to C# coversion http://wp.me/p1hH3Q-2E

I hope it is useful!

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!!

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.