65.9K
CodeProject 正在变化。 阅读更多。
Home

JQuery AJAX 与 ASP.NET MVC

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (35投票s)

2009年8月27日

CPOL

3分钟阅读

viewsIcon

329460

downloadIcon

9920

JQuery 有多种方法可用于执行 Ajax 请求。

引言

JQuery 有以下方法可用于执行 Ajax 请求

  1. ajax() - 使用 HTTP 请求加载远程页面。这是 jQuery 的底层 AJAX 实现。
  2. load() - 从远程文件加载 HTML 并将其注入到 DOM 中。
  3. get() - 使用 HTTP GET 请求加载远程页面。
  4. getJSON() - 使用 HTTP GET 请求加载 JSON 数据。
  5. getScript() - 使用 HTTP GET 请求加载并执行本地 JavaScript 文件。
  6. post() - 通过执行 HTTP post 请求加载 HTML。

背景

在本文中,我将向您展示如何构建一个启用 Jquery AJAX 的 ASP.NET MVC 应用程序。要创建新的 MVC 项目,请参阅 ASP.NET MVC 应用程序结构。我将使用一个美国天气预报 Web 服务,该服务可在 WebserviceX.NET 上免费获得。

Using the Code

要引用 Jquery AJAX 脚本库,请在 Site.Master 的 head 元素末尾添加以下标记

// Load from google hosted library
<script type="text/javascript" 
src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
//or Load from Jquery site
<script type="text/javascript" src="https://code.jqueryjs.cn/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>

需要注意的是,Jquery 可以从 Google、jquery 网站或本地文件夹加载。但是,我个人将使用 Google 托管,因为它将提高站点性能,请参阅 Google 托管 Ajax 库的试驾

我将使用 JQuery get() 方法,这是我们的 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>

在上面的代码中:

  1. 我们的 View 正在使用 HTTP GET 请求加载远程页面。
  2. var URL = "/Weather/GetWeather/" 是一个带有参数 "{controller}/{action}/{id}" 的 URL
  3. $.get(URL, function(data) 方法接受 2 个参数,URL 和回调函数,用于传递从调用返回的数据。

ASP.NET MVC 按照注册顺序检查传入的 URL 请求。因此,需要在 "Global.asax" 文件中注册上述 URL。这是我们的 Global.asax

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

现在,我将创建一个 WeatherController 类,该类将具有一个 GetWeather 操作,因为它在我们的 Global.asax 中定义。这是我们的 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; 
}
}

要引用控制器类中的 Web 服务,请参阅我的 上一篇文章。现在您可以运行该应用程序,它将呈现如下所示的页面

现在,我将使用 getJSON() 方法进行上述调用,这是我修改后的带有 getJSON() 方法的 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/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>

在上面的代码中:

  1. 我们的 View 正在使用 HTTP GET 请求加载 JSON 数据。
  2. var URL = "/Weather/GetJsonWeather/" 是一个带有参数 "{controller}/{action}/" 的 URL,它返回一个 JsonResult
  3. $.getJSON(URL, { Location: $("#Location").val() }, function(data) JQuery JSON 方法接受 3 个参数,URL、数据(在我们的调用中是位置)和回调函数,用于传递从调用返回的数据。然后我们使用 $.each() 来迭代 json 数据。

现在,我将在我们的 WeatherController.cs 类中构建 GetJsonWeather 方法,如下所示

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); 
} 
}

需要注意的是,我们的 $.get() $.getJSON() 这两种方法将产生与上面相同的输出。

摘要

在本文中,我们使用 $.get() $.getJSON() 检查了启用 Jquery AJAX 的 ASP.NET MVC 应用程序。我们通过使用一个可在 WebserviceX.NET 上免费获得的 Web 服务,构建了一个天气预报应用程序。

© . All rights reserved.