使用Html.RenderParital或Html.RenderAction可以在主视图中加载部分视图。
两种方法是有区别的,在"RenderPartial和RenderAction区别"中体验过。
本篇体验使用jquery加载部分视图。
□ HomeController
using System.Web;
using System.Web.Mvc;
using _01.Models;
namespace _01.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ProductPartial()
{
List<Product> products = new List<Product>()
{
new Product(){ID = 1, Name = "产品1", Price = 85.00M},
new Product(){ID = 2, Name = "产品2", Price = 95.00M}
};
return PartialView("_ProductPartial", products);
}
}
}
□ View Model
namespace _01.Models
{
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
□ 部分视图_ProductPartial.cshtml
@model IEnumerable<_01.Models.Product>
@foreach (var item in Model)
{
@item.ID
@item.Name
@item.Price.ToString("c")
<br/>
}
□ 主视图 Index.cshtml
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div id="divProduct"></div>
@section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$.get("@Url.Action("ProductPartial", "Home")", function (data) {
$(‘#divProduct‘).replaceWith(data);
});
});
</script>
}