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

JQuery AJAX with ASP.NET MVC

By , 2 Sep 2009
 

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:

// 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:

<%@ 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.

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.

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:

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

<%@ 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:

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)

About the Author

Farooq Kaiser
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
Member
12+ years of complete software development life cycle experience for web based applications and multi-tier client-server desktop, primarily using LINQ, WCF, WWF, C#, ASP.NET, XML, XSLT, AJAX, Winforms,Visual Basic, JavaScript, JQuery, Google APIs, C++, VB.NET, C, ATL/COM, Open XML. Extensively involved in the requirement analysis, feasibility study, conceptualization, planning, architecture/design, configuration, development, quality assurance, implementation and release of the software products.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 2memberiyer.kumar8323 Feb '13 - 16:29 
Although the code accomplishes what it is supposed to, it seems to encourage fatal design practices:
1. At the first place, you're mixing up javascript and asp.net code:
a. the definition of getWeather() should've been moved out to a separate js
b. onclick must be replaced with something like $('#btnSubmit').click(getWeather)
2. The WeatherController builds the view using StringBuilder. This is pretty shoddy and unclear. The view should've been factored into a separate WeatherResult.ascx, and the controller should just say return View("WeatherResult.ascx", weatherModel)
3. If (2) was done, then even the same shoddy job needn't be done in the javascript: like result = '
<img src="' d.WeatherImage '"> '; etc.
Instead, a simple $("#Result").html(data); would've sufficed.</img>

GeneralMy vote of 5memberLarisa_K17 Jan '13 - 3:28 
Clear and short article. Very good. Thanks a lot.
GeneralMy vote of 5membermanoj kumar choubey16 Jul '12 - 22:34 
Nice
GeneralMy vote of 5memberarif.ict8731 Jul '10 - 2:50 
nice
QuestionHow to acieve the google type search feature ?memberJit00715 Dec '09 - 7:28 
I find it very good for starters. I implemented it and it worked nicely. I was getting confused with other posts. Any way I have a question, how to achieve google type search feature, by on change event of a text box, by typing a character and the simillar items will be shown the drop down form?
GeneralMy vote of 1memberPak5141 Oct '09 - 11:09 
Junk
GeneralThanks for the examplememberiatek14 Sep '09 - 7:08 
I'm new to ASP.NET MVC, but have worked alot with AJAX and JQuery. This was helpful for me to understanding adding Jquery to my ViewEngine
GeneralMy vote of 1memberAcoustic31 Aug '09 - 13:11 
There's almost no explanation of the various jQuery methods, and what code you did provide is just an MVC method. For an article about using jQuery with MVC, there's no meaningful content about either.
GeneralRe: My vote of 1 [modified]memberFarooq 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    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 3 Sep 2009
Article Copyright 2009 by Farooq Kaiser
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid