ASP.NET MVC3 基础教程:第二部分






4.94/5 (9投票s)
如何使用 RenderAction、PartialView 和 jQuery 的 .ajax() 方法创建 MVC3 用户控件。
引言
本文基于 MVC3 基础教程(第一部分),因此请在阅读本文之前先阅读第一部分。本文将解释如何使用 RenderAction、PartialView 和 jQuery 的 .ajax()
方法创建 MVC3 用户控件。
RenderAction
调用子操作方法并在父视图中内联呈现结果。
PartialView
创建一个 PartialViewResult
对象,该对象呈现部分视图,它有助于使用指定的视图呈现视图的一部分。
jQuery 的 .ajax()
执行异步 HTTP (AJAX) 请求并防止回发操作。
重构 ProductController
步骤 1
创建 ProductList
方法并使用 PartialView
返回 ProductModel
的列表。
public virtual ActionResult ProductList()
{
return PartialView("ProductList", AllProducts);
}
类似地,创建 ProductDetail
方法并使用 PartialView
返回 ProductModel
。
public virtual ActionResult ProductDetail(string strPrdCode)
{
int prdCode;
if (!int.TryParse(strPrdCode, out prdCode))
prdCode = 0;
if (prdCode == 0)
prdCode = AllProducts[0].PrdCode;
var prd = model.GetAProduct(prdCode);
return PartialView("ProductDetail", prd);
}
这些代码片段是从 ProductController.cs 的 Index
方法中提取的,现在 Index
方法返回一个空视图。
public ActionResult Index()
{
return View();
}
ProductList 部分视图
第二步
右键单击 ProductController
类中的 ProductList
方法,然后单击“添加视图”菜单。
这将打开“添加视图”窗口,在该窗口中选中“创建为部分视图”复选框,并选择屏幕中的所有字段,如下所示。
它将在 views/Product 文件夹下创建空的 ProductList.cshtml 视图。
步骤 3
从 index.cshtml(来自第 1 部分)复制产品列表 HTML 代码,并将其粘贴到 ProductList.cshtml 文件中,并按如下方式更改操作链接部分。
<span id="@p.PrdCode" style="text-decoration:underline; color:Blue; cursor:hand;"
onclick="javascript:void onLinkClick(@p.PrdCode)" >
@p.Name
</span>
有关详细代码,请参考随附的代码 zip。
ProductDetail 部分视图
步骤 4
与 ProductList
视图类似,通过右键单击 ProductController.css 中的 ProductDetail
方法来创建 ProductDetail
视图。
步骤 5
从 index.cshtml 复制产品详细信息部分 HTML 代码,并将其粘贴到 ProductDetail.cshtml 文件中。
为 POST 操作创建 .ajax() 方法
为了执行异步 HTTP 请求操作,我们可以使用 .ajax()
方法。以下 JavaScript 代码在单击产品列表链接时调用 HTTP POST 请求。
<script language="javascript" type="text/javascript">
function onLinkClick(strPrdCode) {
var product = { 'strPrdCode': strPrdCode };
$.ajax({
type: "POST",
cache: false,
url: 'Product/ProductDetail',
data: product,
success: function (data, xhr, settings) {
$('#ProductDetailDiv').html(data);
},
error: function (xhr, textStatus, error) {
$('#ProductDetailDiv').html(textStatus);
}
});
}
</script>
重构 Index.cshtml
Index.cshtml HTML 代码已移动到 ProductList.cshtml 和 ProductDetail.cshtml,并且添加了 RenderAction
HTML 辅助类来调用这些视图。
<div style="width: 100%">
<div id="ProductListDiv">
@{Html.RenderAction("ProductList");}
</div>
<div id="ProductDetailDiv">
@{Html.RenderAction("ProductDetail");}
</div>
</div>
构建和运行
构建并运行该项目,UI 具有与第 1 部分演示类似的观感,但是当单击产品列表部分中的产品链接时,第 2 部分代码中不会发生页面回发操作。
结论
我希望本文能帮助您理解 jQuery 的 .ajax()
方法与 RenderAction
和 PartialView
概念的基础知识。