Getting JSON-serialized data using Ajax and jQuery in ASP.NET MVC

By: Juan Carlos (John Charles) Olamendy Turruellas

Introduction

In this article, I will show how easily is to get JSON- serialized data from a Web resource using Ajax and jQuery, thus allowing users to interact more with a Web page without being interrupted for a page load event. You can see that ASP.NET MVC Web framework naturally fits with all latest Web 2.0 technologies. As illustration, we’re going to publish a Web resource that serializes using JSON format and sends data concerning Person entities over the wire. Then when the users click on a button of a page, a JavaScript code will call this remote Web resource using Ajax and jQuery technologies. The Web platform is Microsoft ASP.NET MVC.

Getting started with the solution

First of all, we need to open Visual Studio.NET 2008 and create a MVC Application (see Figure 1).

Figure 1

Next step is to define the Person business entity in the HumanResource namespace (see Listing 1).

namespace HumanResources

{

public class Person

{

private string firstname;

public string Firstname

{

get { return firstname; }

set { firstname = value; }

}

 

private string lastname;

public string Lastname

{

get { return lastname; }

set { lastname = value; }

}

 

private int age;

public int Age

{

get { return age; }

set { age = value; }

}

}

}

Listing 1

Then we have to add a controller artifact to the MVC project in order to handle the Web requests to our Web solution. Because our controller is named AsynchronousFilledFormController and due to the default routing rules in MVC applications, we can access to the action methods of this controller through the base address http://localhost:6589/asynchronousfilledform (see Figure 2).

Figure 2

Then we have to define a view for the default Index action method of this controller. So, right-click on the Index method and select Add View option from the context menu (see Figure 3).

Figure 3

The Add View dialog box appears, and the click on the Add button (see Figure 4).

Figure 4

Next step is to go to the Index.aspx view, and add a form with a button. When the user clicks on the button, then a JavaScript function (fillButtonOnClickHandler) with jQuery logic will access a Web resource (/asynchronousfilledform/getperson/) using HTTP GET verb, get an object serialized using JSON format,  and finally call a callback function to show the JSON-serialized data in an alert message. All these operations are executed asynchronously (see Listing 2).

<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage” %>

 

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>

Index

</asp:Content>

 

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

<script language=”javascript” type=”text/javascript”>

$(function(){

$(“#fillingbutton”).click(fillButtonOnClickHandler);

});

function fillButtonOnClickHandler(){

$.get(“/asynchronousfilledform/getperson/”, null,

function(data){alert(data);

});

}

</script>

<h2>Asynchronous form</h2>

<div>

<form action=”” id=”myform”>

<input type=”button” id=”fillingbutton” value=”Fill the Form” />

</form>

</div>

</asp:Content>

Listing 2

In order to use successfully the jQuery JavaScript library, we need to include this library in the head element of the Web page. This accomplished on the Site.Master page (highlighted in yellow) (see Listing 3).

<%@ Master Language=”C#” Inherits=”System.Web.Mvc.ViewMasterPage” %>

 

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

<title><asp:ContentPlaceHolder ID=”TitleContent” runat=”server” /></title>

<link href=”../../Content/Site.css” rel=”stylesheet” type=”text/css” />

<script language=”javascript” type=”text/javascript” src=”../../Scripts/jquery-1.3.2.js”></script>

</head>

 

<body>

<div>

 

<div id=”header”>

<div id=”title”>

<h1>My MVC Application</h1>

</div>

<div id=”logindisplay”>

<% Html.RenderPartial(“LogOnUserControl”); %>

</div>

<div id=”menucontainer”>

<ul id=”menu”>

<li><%= Html.ActionLink(“Home”, “Index”, “Home”)%></li>

<li><%= Html.ActionLink(“About”, “About”, “Home”)%></li>

</ul>

</div>

</div>

 

<div id=”main”>

<asp:ContentPlaceHolder ID=”MainContent” runat=”server” />

 

<div id=”footer”>

</div>

</div>

</div>

</body>

</html>

Listing 3

The last step of the solution is to include the GetPerson action method on the controller to handle the GET HTTP request on the resource pointing to for the /asynchronousfilledform/getperson/ URI in order to get data concerning person entities (highlighted in yellow in the Listing 4).

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

using HumanResources;

 

namespace AjaxMvcApp.Controllers

{

public class AsynchronousFilledFormController : Controller

{

//

// GET: /AsynchronousFilledForm/

 

public ActionResult Index()

{

return View();

}

 

public ActionResult GetPerson()

{

Person objPerson = new Person();

objPerson.Firstname = “John”;

objPerson.Lastname = “Doe”;

objPerson.Age = 30;

return Json(objPerson);

}

}

}

Listing 4

Then we run the application, click on the Fill the Form button and see the results (see Figure 5).

Figure 5

Using the Firebug plug-in for Mozila FireFox, you can see the request and response headers (see Figure 6).

Figure 6

As well as the response content (see Figure 7).

Figure 7

Conclusion

In this article, I’ve illustrated how easily is to get JSON- serialized data from a Web resource using Ajax and jQuery in ASP.NET MVC.

About these ads

3 thoughts on “Getting JSON-serialized data using Ajax and jQuery in ASP.NET MVC

  1. Pingback: Tech-no-logy Demystified with Sandeep Joshi

  2. Pingback: MVP Factor

  3. Pingback: Fernando Garcia Lorea

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s