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

JQuery AJAX with ASP.NET MVC

, 2 Sep 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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

Share

About the Author

Farooq Kaiser
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
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.

Comments and Discussions

 
GeneralMy vote of 1 PinmemberMember 1121064920-Dec-14 0:30 
NewsRewrote article (second live) after import project didn't work. Pinprofessional4Dinand26-Dec-14 23:47 
GeneralCannot run the application PinmemberTAN TH27-Apr-14 16:23 
GeneralMy vote of 5 PinmemberManojKumarUdayali20-Feb-14 21:10 
GeneralMy vote of 2 Pinmemberiyer.kumar8323-Feb-13 17:29 
GeneralMy vote of 5 PinmemberLarisa_K17-Jan-13 4:28 
GeneralMy vote of 5 Pinmembermanoj kumar choubey16-Jul-12 23:34 
GeneralMy vote of 5 Pinmemberarif.ict8731-Jul-10 3:50 
nice
QuestionHow to acieve the google type search feature ? PinmemberJit00715-Dec-09 8:28 
GeneralMy vote of 1 PinmemberPak5141-Oct-09 12:09 

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.141223.1 | Last Updated 3 Sep 2009
Article Copyright 2009 by Farooq Kaiser
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid