Click here to Skip to main content
15,867,991 members
Articles / Web Development / XHTML

JQuery AJAX with ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.78/5 (40 votes)
2 Sep 2009CPOL3 min read 325.1K   9.9K   115   15
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)


Written By
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWeather project problem Pin
Member 125526898-Jun-16 22:51
Member 125526898-Jun-16 22:51 
QuestionHow to call Bootstrap model from mvc actionResult Pin
Member 1124778430-Oct-15 10:23
Member 1124778430-Oct-15 10:23 
GeneralMy vote of 1 Pin
Member 1121064919-Dec-14 23:30
Member 1121064919-Dec-14 23:30 
NewsRewrote article (second live) after import project didn't work. Pin
Dinand.dotnet6-Dec-14 22:47
professionalDinand.dotnet6-Dec-14 22:47 
GeneralCannot run the application Pin
TAN TH27-Apr-14 15:23
TAN TH27-Apr-14 15:23 
GeneralMy vote of 5 Pin
ManojKumarUdayali20-Feb-14 20:10
professionalManojKumarUdayali20-Feb-14 20:10 
GeneralMy vote of 2 Pin
iyer.kumar23-Feb-13 16:29
iyer.kumar23-Feb-13 16:29 
GeneralMy vote of 5 Pin
Larisa_K17-Jan-13 3:28
Larisa_K17-Jan-13 3:28 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey16-Jul-12 22:34
professionalManoj Kumar Choubey16-Jul-12 22:34 
GeneralMy vote of 5 Pin
Ariful Islam Sabuz31-Jul-10 2:50
Ariful Islam Sabuz31-Jul-10 2:50 
QuestionHow to acieve the google type search feature ? Pin
Jit00715-Dec-09 7:28
Jit00715-Dec-09 7:28 
GeneralMy vote of 1 Pin
asdqwewqe1-Oct-09 11:09
asdqwewqe1-Oct-09 11:09 
GeneralThanks for the example Pin
iatek14-Sep-09 7:08
iatek14-Sep-09 7:08 
GeneralMy vote of 1 Pin
TylerBrinks31-Aug-09 13:11
TylerBrinks31-Aug-09 13:11 
GeneralRe: My vote of 1 [modified] Pin
Farooq Kaiser31-Aug-09 16:59
professionalFarooq Kaiser31-Aug-09 16:59 
Hi there,
I guess you did not read the full article, if you read the artcle and I'm using jquery get() method.
Even it has a full source code and it is explained as shown below.

In the above code: 

Our view is loading a remote page using an HTTP GET request. 
var URL = "/Weather/GetWeather/" is a URL with parameters "{controller}/{action}/{id}" 
$.get(URL, function(data) The 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.


modified on Monday, August 31, 2009 11:05 PM

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

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