Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / XHTML

JQuery AJAX with ASP.NET MVC

4.78/5 (40 votes)
2 Sep 2009CPOL3 min read 327.9K   9.9K  
The JQuery has several methods that can be used to perform Ajax requests

Introduction

The JQuery has the following methods that can be used to perform Ajax requests:

  1. ajax() - Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation.
  2. load() - Load HTML from a remote file and inject it into the DOM.
  3. get() - Load a remote page using an HTTP GET request.
  4. getJSON() - Load JSON data using an HTTP GET request.
  5. getScript() - Loads, and executes, a local JavaScript file using an HTTP GET request.
  6. post() - Loads HTML by performing an HTTP post request.

Background

In this article, I will show you how to build a Jquery AJAX enabled ASP.NET MVC application. To create a new MVC project, see ASP.NET MVC application structure. I will consume a USA Weather Forecast web service which is freely available at WebserviceX.NET.

Using the Code

To reference the Jquery AJAX script libraries, add the following markup at the end of the head element in Site.Master:

JavaScript
// Load from google hosted library
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
//or Load from Jquery site
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
//or Load from Scripts folder of the Visual Studio ASP.NET MVC template
<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript"></script>

One thing to note is that Jquery can be loaded from Google, jquery site or a local folder. However, I will personally use Google hosted as it will improve the site performance, see Test Drive of the Google Hosted Ajax Libraries.

I will use JQuery get() method and here is our View:

ASP.NET
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
	Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function getWeather() {
var URL = "/Weather/GetWeather/" + $("#Location").val(); 
$.get(URL, function(data) {
$("#Result").html(data);
}); 
}
</script>
<div>
<input type="text" id="Location" style="width: 325px" /> 
<input type="button" id="btnSubmit" value="Get Weather" 
	onclick="javascript:getWeather();" /> 
<br /> <br />
<div id="Result"></div>
</div>
</asp:Content>

In the above code:

  1. Our view is loading a remote page using an HTTP GET request.
  2. var URL = "/Weather/GetWeather/" is a URL with parameters "{controller}/{action}/{id}"
  3. $.get(URL, function(data) method takes 2 parameters, URL and the callback function to pass the data returned from the call.

ASP.NET MVC checks incoming URL requests against routes in the order they were registered. Therefore, the above URL is required to register in the "Global.asax" file. Here is our Global.asax.

C#
routes.MapRoute("Jquery", "Weather/GetWeather/{Id}",
                      new { controller = "Weather", action = "GetWeather" });

Now, I will create a WeatherController class that will have a GetWeather action as it is defined in our Global.asax. Here is our WeatherController.cs.

C#
public class WeatherController : Controller
{
//
// GET: /Weather/
public ActionResult Index()
{
return View();
}
public ActionResult GetWeather(string Id)
{
StringBuilder sb = new StringBuilder(); 
WeatherForecast wf = new WeatherForecast();
WeatherForecasts wfs = wf.GetWeatherByPlaceName(Id);
WeatherData[] wd = wfs.Details;
sb.AppendFormat("<B>Weather Forecast for {0}</B><br /><br />", wfs.PlaceName);
foreach (WeatherData d in wd)
{
if(!string.IsNullOrEmpty(d.WeatherImage))
{
sb.AppendFormat("<img src=\"{0}\" >", d.WeatherImage);
sb.AppendFormat(" {0}", d.Day);
sb.AppendFormat(", High {0}F", d.MaxTemperatureF);
sb.AppendFormat(", Low {0}F<br />", d.MinTemperatureF);
}
}
Response.Write(sb.ToString());
return null; 
}
}

To reference the web service in our controller class, see my previous article. Now you can run the application and it will render the page as shown below:

Image 1

Now, I will use the getJSON() method to make the above call and here is my modified view with getJSON() method as shown below:

ASP.NET
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
	Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function getWeather() {
var URL = "/Weather/GetJsonWeather/";
$.getJSON(URL, { Location: $("#Location").val() }, function(data) {
var result = "";
$.each(data, function(index, d) {
if (d.WeatherImage != '') {
result += '<br \><img src="' + d.WeatherImage + '" > ';
result += d.Day;
result += ', High ' + d.MaxTemperatureF + 'F';
result += ', Low ' + d.MinTemperatureF + 'F';
}
});
$("#Result").html(result);
});
}
</script>
<div>
<input type="text" id="Location" style="width: 325px" /> 
<input type="button" id="btnSubmit" 
	value="Get Weather" onclick="javascript:getWeather();" /> 
<br /> <br />
<div id="Result"></div>
</div>
</asp:Content>

In the above code:

  1. Our view is loading JSON data using an HTTP GET request.
  2. var URL = "/Weather/GetJsonWeather/" is a URL with parameters "{controller}/{action}/" that returns a JsonResult.
  3. $.getJSON(URL, { Location: $("#Location").val() }, function(data) JQuery JSON method takes 3 parameters, URL, data (which is location in our call) and the callback function to pass the data returned from the call. Then we use $.each() to iterate the json data.

Now, I will build GetJsonWeather method in our WeatherController.cs class as shown below:

C#
public class WeatherController : Controller
{
//
// GET: /Weather/

public ActionResult Index()
{
return View();
}

public JsonResult GetJsonWeather(string location)
{
WeatherForecast wf = new WeatherForecast();
WeatherForecasts wfs = wf.GetWeatherByPlaceName(location);
return Json(wfs.Details); 
} 
}

One thing to note is that our both methods $.get() and $.getJSON() will produce the same output as shown above.

Summary

In this article, we examined Jquery AJAX enabled ASP.NET MVC application using $.get() and $.getJSON(). We built a Weather forecast application by consuming a web service which is freely available at WebserviceX.NET.

License

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