Click here to Skip to main content
Click here to Skip to main content

JSON and Microsoft technologies

, 13 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
In this article we will understand what is JSON and how to work with it using Asp.NET Web Forms, Asp.NET MVC, WCF and finally Web API

Introduction

In this article we will understand the concept of JSON and then do some labs and learn how JavaScript communicate with different Microsoft technologies (like Asp.Net MVC, WCF, Web API and Asp.net Web Forms) with the help of JSON.

(It take huge effort to write such kind of article. Please comment and vote if this article seems useful for you. Click here to find more).

what we will learn today?

What is JavaScript Object?

In the world of JavaScript we have only two things. Variables and functions.
“Variables hold the data and function are some special actions to be performed.”

Variables may be of type int, string, and float or may be of type object.

“JavaScript objects are simply variables which hold up variables and functions into one unit and bring up encapsulation into life.”

Lab 1 – Understand JavaScript object

In order to understand JavaScript object it’s not required to create a large Asp.net MVC or Web Form project. We can do that with a simple HTML file

Step 1. Open Visual studio. Click File >> New >> File. Select HTML in the next screen

Step 2.Create JavaScript object as follows.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">
        var Customer =
            {
               Name: 'Anan Kumar', Address: 'USA'
            };
    </script>
</head>
<body>
</body>
</html>

Step 3.Access the Properties inside JavaScript object using “dot (.)” syntax as follows.

alert(Customer.Name);

Step 4.Say Cntr+S, Provide some meaningful name and save the file.

Step 5.Open the HTML file using your favorite user and test the application.

Output

Lab 2 – Array JavaScript objects

Arrays – Defined as collection of elements of same type. Good news is even array of JavaScript object is possible.

Step 1.First step is going to be same as above.

Step 2.Next step is create a JavaScript object array as follows and access it

var Customers =
    [
        {
            Name: 'Anan Kumar', Address: 'USA'
        },
        {
            Name: 'Rajav Kiran', Address: 'UK'
        },
        {
            Name: 'Pappu Dabbawala', Address: 'USA'
        }
    ];


alert(Customers[0].Name);

Step 3.Save, Execute and test page.

What is XML and Why XML?

In the above image a man and a dog is trying to talk to each other. Will they understand each other? Answer is simply No. Both of them have their own way of transferring messages. What one knows, other can’t understand.

What’s the solution?

Only Solution is to have some common standards. If both of them can pass messages to each other in a format which both can understand problem is solved.

Look around. Every time we see two different heterogeneous system talking to each other, we will see some common standard.

We talk with our friends not only just using a common known language (like English) but also using proper grammar. When we want to talk with our computer we write “Programs” (we know how to write program and compiler knows how to read it).

XML

XML or commonly known as Extensible markup language is a standard we represent the data/messages which can be passed across. In this internet world, communication plays an important role. Especially communication between two heterogeneous systems.

XML is simply a standard format in which data and messages will be represented and transferred across. Every system/technology knows about XML and can understand XML.

Simple Example of XML format?

Let say we have “Customer information (Customer Name, Address and Age)” and we want to transfer that information across internet or may be transfer from one technology to another. First step will be representing customer information in xml format which will be as follows.

<Customer>
  <CustomerName>Russel Fernandes</CustomerName>
  <CustomerAddress>New York </CustomerAddress>
  <CustomreAge>56</CustomerAge>
</Customer>

Representing multiple customers using XML?

<Customers>
   <Customer>
       <CustomerName>Russel Fernandes</CustomerName>
       <CustomerAddress>New York </CustomerAddress>
       <CustomreAge>56</CustomerAge>
   </Customer>
   <Customer>
        <CustomerName>Rajesh Mishra</CustomerName>
        <CustomerAddress>India</CustomerAddress>
        <CustomreAge>59</CustomerAge>
    </Customer>
</Customers>

What are the problem or disadvantages of XML?

There are two major disadvantages with XML.

  1. Difficulties in XML Parsing - For some light weight technologies like JavaScript XML parsing is not very easy. Once it get the XML string emitted from other technologies it get the values (data) inside it with the help of custom logic.
  2. More Fat – look at the structure of the customer data represented as xml in above example. We can easily see many unnecessary tags attached to it. XML is comparatively heavy weight compared to JSON about who we will speak next.

What is JSON?

JSON commonly known as JavaScript Object notation is another standard for exchanging data between two different technologies.

How to represent data in JSON?

This is the best part J it’s same like JavaScript object.

var JsonCustomerString = '{"Name": "Anan Kumar", "Address": "USA"}';

How to represent collection of data in JSON?

Nothing new compared to JavaScript object.

var JsonCustomerString = '[{"Name": "Anan Kumar", "Address": "USA"},{"Name": "Rajav Kiran", "Address": "UK"},{"Name": "Pappu Dabbawala", "Address": "USA"}]';

Is it same as JavaScript object?

Not, it just a format in which we can represent data whereas JavaScript object is a variable which actually holds our data. There is no direct relation between JavaScript object and JSON. JSON is called as JavaScript object notation because JSONS structure looks like JavaScript object.

What are the advantages of JSON?

  • JSON is very simple. It’s just a key value pair. In XML as we saw earlier we end up with writing too many other things. JSON is light weight compare to XML
  • Just like XML its platform independent. Almost all modern technologies has the ability to read and understand it.
  • Data represented in the form of JSON can be easily transformed into JavaScript object and thus it will be easier for JavaScript to handle that data.

Lab 3 – Converting JSON string to JavaScript object

Step 1.Create a new HTML file just like above.

Step 2.Define two JSON strings as below.

Simple Json string:

var JsonCustomerString = '{"Name": "Anan Kumar", "Address": "USA"}';

Json string containing collection of customers:

var JsonCustomerCollectionString = '[{"Name": "Anan Kumar", "Address": "USA"},{"Name": "Rajav Kiran", "Address": "UK"},{"Name": "Pappu Dabbawala", "Address": "USA"}]';

Step 3.Convert JSON String to JavaScript object using JSON.parse method in JavaScript.

  var Customer = JSON.parse(JsonCustomerString);

  var Customers = JSON.parse(JsonCustomerCollectionString);

Step 4.Write following code to access the elements in the JavaScript Object.

alert(Customer.Name);

alert(Customers[0].Name);

Step 5.Save, Execute and Test the page.

 

 

Note: In real life scenario this kind of JSON string will be emitted by different server side technologies like Asp. NET Web Form, Asp.NET MVC, WCF, Asp.NET Web API, PHP, Java etc.

Best part is some server technology automatically handle the conversion part. For example when JavaScript object is directly passed from client side, first it will be converted to JSON string automatically and when received at server side, it will be automatically converted to native type. It may happen vice versa.

From here, one lab will be dedicated for one kind of Microsoft technology which will emit JSON string. From JavaScript using jQuery we will consume this JSON string and with it as a JavaScript Object.

Initial setup:

We have a custom C# class created with us called Customer.

namespace JSONExamples
{
    public class Customer
    {
        public string CustomerName { get; set; }
        public string Address { get; set; }
    }
}

Working with Asp.NET Web Forms

In asp.net Web Forms we will make use of HTTP handlers.

Lab 4 - Get Request - Get JSON from Asp.Net Web Form into JavaScript world

Step 1. Create a Web Application Project.

Click File>>New>>Project. Select Asp.net Empty Web Application project from the dialog box.

Step 2. Create HTTP Handler.

Right click the wen Form project created and click Add>>New Item. Select Generic Handler (with ashx extension), Name is CustomerWebForm.ashx and say OK.

Step 3. Modify Process request and emit JSON string.

Open the newly created ashx file and inside ProcessRequest function do following things.

  1. Create a Customer class object and assign values to its properties
Customer customer = new Customer()
{
    CustomerName="Raju Mishra",
    Address="UP"
};
  1. Create JSON string of above object using System.Web.Script.Serialization.JavaScriptSerialzier
JavaScriptSerializer serializer = new JavaScriptSerializer();
string JsonCustomerString=serializer.Serialize(customer);
  1. Change the Content type of Response from text/plain to text/json
context.Response.ContentType = "text/json";
  1. Write the Converted string to Output stream
context.Response.Write(JsonCustomerString);

Step 4. Create Client code for consuming JSON data.

  1. Add new item to project. This time it will be simple aspx web form.

    Right click the project. Click>>Add New Item. Select Web Form, name it CustomerClient.aspx and say ok.

  2. Download jQuery from the Nugest Package or from Jquery.com and reference it in the page.
    <script src="Scripts/jquery-2.1.1.js"></script>
  3. Create a simple input button in the webform and attach JavaScript onclick event to it as follows.
    <input type="button" name="BtnClickMe" value="ClickMe" onclick="DisplayJSON();" />
  4. In the head section create a script tag and add following script into it.
    <script type="text/javascript">
        function DisplayJSON()
        {
            $.getJSON("CustomerWebForm.ashx").done(function (d)
            {
                alert(d.CustomerName);
            });
        }
    </script>

Step 5. Execute and Test

Press F5 and execute the application.

Click the “Click me” button and check the output.

Lab 5 - Post Request - Post JSON to Asp.Net web Form world from JavaScript world

Step 1. Create handler for post request

In the same project create a one more handler called CustomerPost.ashx.

Step 2. Get the post data in process request

Write following code inside ProcesRequest

string JSONCustomerString = context.Request.Form["Customer"];

JavaScriptSerializer serializer = new JavaScriptSerializer();
Customer customer=serializer.Deserialize<Customer>(JSONCustomerString);

context.Response.ContentType = "text/plain";
context.Response.Write("Customer recieved from client side : "+customer.CustomerName);  

Step 3. Create client code for posting JSON data

  1. Add one more button inside same aspx page created in last demo.
    <input type="button" name="BtnPostMe" value="Click To Post" onclick="PostJson();" />
  2. In the head section add the following JavaScript code.
    function PostJson()
    {
         var customer={CustomerName:"ClientCustomer",Address:"Cient Address"};
         $.post("CustomerPost.ashx", "Customer="+JSON.stringify(customer)).done(function (d)
         {
            alert(d);
         });
     }
    

Step 4. Execute and Test the application.

Press F5 and execute the application. Click the “Click To Post” button and check the output.

Now you know,

  • How to make a communication between JavaScript and Web Forms.
  • How to pass data between two technologies.

Now let’s do the same thing with Asp.net MVC.

Working with Asp.NET MVC

Lab 6 - Get Request - Get JSON from Asp.Net MVC into JavaScript world

Step 1. Create MVC4 Web Application Project.

Click File>>New>>Project. Select Asp.net MVC4 Web Application. From the project template select Empty.

Step 2. Create Controller and Action Method.

  1. Create a Controller called JsonTestController.
  2. Create an action method called Index as follows.
    public ActionResult Index()
    {
        return View();
    }
        
  3. Create an action method called JsonData.
  4. In that action method create object of customer class and assign values to its properties.
  5. Call Json method available in the Base class “Controller”. Json method will create JsonResult object that serializes customer object to to JSON.
    public ActionResult JsonData()
    {
        Customer customer = new Customer()
        {
            CustomerName = "Abram",
            Address = "Russia"
        };
        return Json(customer ,JsonRequestBehavior.AllowGet));
    }

Step 3. Create Client code for consuming JSON data.

  1. Right click the Index Action, select Add View and create a view called Index.

  2. Do the same thing which we did in Web Form project.

    i. Reference jQuery in the view

    ii. Create a input button and set its onclick property to “DisplayJSON();”

    iii. Create a DisplayJSON javascript function in the head as follows

    function DisplayJSON()
    {
        $.getJSON("@Url.Content("~/JsonTest/JsonData")").done(function (d)
        {
            alert(d.CustomerName);
        });
    }

Step 4. Execute and Test application

Press F5 and execute the application. Execute Index View. Click the “ClickMe” button.

Lab 7 - Post Request - Post JSON to Asp.Net MVC World from JavaScript world

Step 1. Create Action method for post request

In the same controller create a one more Action method as follows.

public string JsonPost(Customer customer)
{
    return "Customer recieved from client side : " + customer.CustomerName;
}

Step 2. Create client code for posting JSON data

  1. Add one more button inside same aspx page created in last demo.
    <input type="button" name="BtnPostMe" value="Click To Post" onclick="PostJson();" />
  2. In the head section add the following JavaScript code.
    function PostJson()
    {
        var customer = { CustomerName: "ClientCustomer", Address: "Cient Address" };
        $.post("@Url.Content("~/JsonTest/JsonPost")", customer).done(function (d)
        {
            alert(d);
        });
    }

Note: When working with Asp.NET MVC it’s not required to explicitly convert JavaScript object to Json String and vice versa. It internally get handled.

Look and compare both server and client code of Web Forms with MVC. MVC had made things simpler.

Step 3. Execute and Test the application

Press F5 and execute the application. Click the “Click To Post” button and check the output.

Working with WCF REST services

Our next server side technology will be WCF Rest. So lets the ball rolling

Lab 8 - Get Request - Get JSON from WCF Rest into JavaScript world

Step 1. Create WCF Project

Click File>>New>>Project. Select WCF and the WCF Service Application. Name the Project as WCFJSON and say ok.

Step 2. Remove unnecessary files

Remove IService1.cs and Service1.svc from the project.

 

 

Step 3. Create new Service.

Right click the project. Say Add >> New Item. Select WCF Service. Name is as JsonTest and say ok.

It will create two things in the project. IJsonTest.cs which is our service contract and JsonTest.svc which is our Service.

Step 4. Create operation Contract

Open IJsonTest.cs and a method called GetJSONData inside it as follows.

[OperationContract]
Customer GetJsonData();

Step 5. Implement Opearation Contract

Open JsonTest.svc and implement GetJsonData method as follows.

public Customer GetJsonData()
{
    Customer customer = new Customer()
    {
        CustomerName = "benazir bhutto",
        Address = "Pakistan"
    };
    return customer;
}

Step 6. Create a Rest end point

  1. Open the web.config file
  2. Navigate to System.ServiceModel section
<system.serviceModel>

&hellip; 

</system.serviceModel>
  1. Inside it add new Services Tag. Inside Services add Service Tag and point it to the service we created.
<system.serviceModel>
  <services>
    <service name="WCFJSON.JsonTest" >
&hellip;
    </service>
  </services>
  1. Inside service configure endpoint with WebHttpBinding as follows.
<endpoint binding="webHttpBinding" address="Rest" contract="WCFJSON.IJsonTest"
behaviorConfiguration="MyRestBehavior"></endpoint>

Step 7. Mark the Operation Contract WCF rest operation

Add WebInvoke attribute to the GetJsonData as follows,

[WebInvoke(Method="GET",ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare,
    UriTemplate="GetJsonTestData")]
public Customer GetJsonData()
{&hellip;.

Step 8. Create a client code for consuming Json data

  1. Create a simple HTML File called WCFRestClient.HTML and reference jQuery in it.

Note: For demonstration purpose we are keeping HTML file inside the same WCF project.

  1. Just like previous labs add one button (called “Click Me”) in the HTML page which will invoke a JavaScript function called DisplayCustomer which will look like follow.
function DisplayJSON()

{

    $.getJSON("http://localhost:10647/JsonTest.svc/Rest/GetJsonTestData").done(function (d)

    {

        alert(d.CustomerName);

    });

}

Step 9. Execute and Test.

Press F5. Navigate to WcfRestClient.html. Click the “Click Me” button.

Lab 9 - Post Request - Send JSON to WCF Rest from JavaScript world

Step 1. Create new operation contract

In the same service contract create one more opearation contract called PostJsonData as follows

[OperationContract]
string PostJsonData(Customer customer);

Step 2. Implement the service contract

public string PostJsonData(Customer customer)
{
    return customer.CustomerName;
}

Step 3. Mark the Operation Contract WCF rest operation

Add WebInvoke Attribute to the implemented Operation contract. Make sure to set method to “POST”.

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json,
UriTemplate = "PostJsonTestData")]
public string PostJsonData(Customer customer)

Step 4. Create a client code for posting Json data.

We will utilize the same HTML file created in last lab (Get WCF Demo).

  1. Add a one more input button and onclick of that button invoke a JavaScript button called PostJSON.
  2. This time we cannot use jQuery’s “$.post” method because for WCF Rest we have to set request content type to “application/json” and which is not supported by “$.post” function. We will use core jQuery Ajax function $.ajax as follows.
function PostJSON()
{
    var Customer = { CustomerName: 'Fernandese', Address: 'Delhi' };
    $.ajax({
        type: "POST",
        url: "http://localhost:10647/JsonTest.svc/Rest/PostJsonTestData",
        data: JSON.stringify(Customer),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, status, jqXHR)
        {
            alert(data);
        },
        error: function (xhr)
        {
            alert(xhr.responseText);
        }
    });
}

Step 5. Execute and Test the application
Press F5 and execute the application.

Working Asp.NET Web API

As we know WCF Rest let us create HTTP services. The main intent behind WCF was to support SOA. For HTTP services in Microsoft world we have Asp.NET Web API.

We will talk about Web API and WCF Rest in detail in future article. For now let’s concentrate on communication between Asp.NET WebAPI and JavaScript.

Lab 9 – Get Request – Send Json from Asp.Net WebAPI to JavaScript world.

Step 1. Create Web API project

Open Visual studio. Click File>>New>>Project. Select Asp.Net MVC4 Web Application. From the Template selection dialog box select WebAPI and Say OK.

Step 2. Remove all unnecessary files.

Remove all existing Controllers, Views and CSS files from the project.

Step 3. Create API controller

  1. Right click the controller click Add>>Controller.
  2. In the Add Controller dialog box enter controller name it as “JsonController”.
  3. Select “Empty API Controller” Template.
  4. Click OK.

Step 4. Create Action method

In the JsonController you will find the base class is APIController.

Create a method called GET in the controller as follows.

public Customer Get()
{
    Customer customer =  new Customer()
    {
        CustomerName="Rajesh Oja",
        Address="Nepal"
    };
    return customer;
}

Step 5. Create client code for Consuming Json Data.

  1. Create a new controller called TestingController. Make sure base class is Controller this time. It should not be ApiController.
  2. Create an action method called Index as follows.
    public ActionResult Index()
    {
        return View();
    }
  3. Right the action method and say add view. Keep View name as “index” and say Ok.
  4. In the newly created view reference jQuery.
  5. Now create a simple input button and on click of that invoke a JavaScript function called “DisplayJSON” which looks like follows.
  6. In the head section of View add a script tag and creare DisplayJSON function as follows.
    function DisplayJSON() 
    {
        $.getJSON("@Url.Content("~/api/Json")").done(function (d)
        {
            alert(d.CustomerName);
        });
    }

Step 6. Execute and Test the application
Press F5 and execute the application.

Lab 10 – Post Request – Send Json to Asp.Net WebAPI from JavaScript world.

Step 1. Create a Post action

In the JsonController created in the above step add a new method as follows.

public string Post(Customer customer)
{
    return customer.CustomerName;
}

Step 2. Create a client code for positing JsonData.

  1. In the same Testing view add one more input button call it “Click to Post”.
  2. In the on click of this button invoke a JavaScript function called “PostJSON”.
  3. In the head section of the View, inside script tag, add “PostJSON” method as follows.
function PostJSON()
{
    var Customer = { CustomerName: 'Karan Kumar', Address: 'Karnataka' };       
    $.post("@Url.Content("~/api/Json")", Customer).done
    (
        function (d)
        {
            alert(d);
        }
    );
}

Step 3. Execute and Test the application

Finally we are done with most of the Microsoft technologies.

If you want to kick start with Jquery, play with the below video: -

Conclusion

In this article we learned about Json, Its advantages and how JSON makes communication between Javascript world and different Microsoft world simpler.

Hope you enjoyed reading this. Your comments, votes and suggestions motivates us for writing more stuffs like this.

For technical trainings on various topics like WCF, MVC, Business Intelligence, Design Patterns, WPF and UML and many more feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this click here. Subscribe to article updates or follow at twitter @SukeshMarla

See 600+ above FAQ questions and answers in .NET, C#, ASP.NET, SQL, WCF, WPF, WWF, SharePoint, Design patterns, UML etc.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Marla Sukesh
Technical Lead ShawMan Softwares
India India
Learning is fun but teaching is awesome.
 
Code re-usability is my passion ,Teaching and learning is my hobby, Becoming an successful entrepreneur is my goal.
 

For technical trainings on various topics like WCF, MVC, Business Intelligence, Design Patterns, WPF and UML and many more feel free to contact SukeshMarla@Gmail.com or visit justcompile.com or visit www.sukesh-marla.com

 

@Twitter
@Facebook
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 Pinmembermajid torfi27-Oct-14 23:43 
GeneralMy vote of 5 Pinmembersrikanth42413-Oct-14 3:31 
GeneralRe: My vote of 5 Pinprofessional Marla Sukesh13-Oct-14 22:33 
GeneralMy vote of 5 Pinmemberharveyt30-Sep-14 19:15 
GeneralRe: My vote of 5 Pinprofessional Marla Sukesh13-Oct-14 22:34 
QuestionNice... How about windows 9 PinmemberBMEP23-Sep-14 22:24 
AnswerRe: Nice... How about windows 9 Pinprofessionalaarif moh shaikh4-Oct-14 3:27 
QuestionParsing Json PinmemberAnil000727-Jul-14 20:56 
GeneralThank You PinmemberMember 938642623-Jul-14 14:21 
SuggestionRegarding the Model Pinmemberkumarbs23-Jul-14 1:23 
GeneralMy vote of 5 PinmvpAkhil Mittal13-Jul-14 19:59 
GeneralRe: My vote of 5 Pinprofessional Marla Sukesh13-Jul-14 20:18 
QuestionBug: alert(Customers[1].Name); Pinmemberdanmorin1-Jul-14 6:23 
AnswerRe: Bug: alert(Customers[1].Name); Pinmemberalaa9jo8-Jul-14 1:54 
GeneralRe: Bug: alert(Customers[1].Name); Pinprofessional Marla Sukesh13-Jul-14 8:31 
QuestionGood work! PinprofessionalVolynsky Alex26-Jun-14 2:03 
AnswerRe: Good work! PinprofessionalMarla Sukesh27-Jun-14 19:04 
GeneralRe: Good work! PinprofessionalVolynsky Alex27-Jun-14 23:29 
GeneralMy 5 PinprofessionalShahriar Iqbal Chowdhury/Galib25-Jun-14 21:28 
GeneralMy vote of 4 PinmemberShafiqur Rahman, Banladesh25-Jun-14 20:17 
GeneralNice PinmemberShafiqur Rahman, Banladesh25-Jun-14 20:11 
Questionneed example of JSON with database query PinmemberMahesh Babu23-Jun-14 17:43 
GeneralMy vote of 5 PinprofessionalRenju Vinod16-Jun-14 1:44 
QuestionAbout Lab 8 PinmemberMember 1088410014-Jun-14 2:33 
Generalmy vote is 5 PinmemberMd Shahriar Hasan Sahad11-Jun-14 22:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 13 Jul 2014
Article Copyright 2014 by Marla Sukesh
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid