Introduction
The JQuery has the following methods that can be used to perform Ajax requests:
ajax()
- Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation. load()
- Load HTML from a remote file and inject it into the DOM. get()
- Load a remote page using an HTTP GET
request. getJSON()
- Load JSON data using an HTTP GET
request. getScript()
- Loads, and executes, a local JavaScript file using an HTTP GET
request. 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
:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<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:
- 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)
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
{
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:
- Our view is loading JSON data using an HTTP
GET
request. var URL = "/Weather/GetJsonWeather/"
is a URL with parameters "{controller}/{action}/"
that returns a JsonResult
. $.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
{
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.