Partial View 顧名思義就是Html代碼片斷,所以能夠用Partial View 把部分的Html或顯示邏輯包裝起來,方便屢次使用。
Partial View 須要放在Views/Shared 目錄下,任何Controlller 下的Action 或 View 均可以載入。
如何載入Partial View?
MVC 的 HTML 輔助方法有個專門的方法載入分部View,方法名稱爲Partial.
方法原型 |
使用範例
|
Partial(HtmlHelper,String)
|
Html.Partial("CustomerListControl") |
Partial(HtmlHelper,string,Object)
|
Html.Partial("CustomerListControl",Model)
|
Partial(HtmlHelper,string,ViewDataDictionary)
|
Html.Partial("CustomerListControl",ViewData["Model"])
|
Partial(HtmlHelper,string,Object,ViewDataDictionary)
|
Html.Partial("CustomerListControl",Model,ViewData["Model"])
|
public ActionResult CustomerListControl()
{
Return PartialView();
}
@Html.Action("CustomerListControl")
如何實現?
1 Models
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Step1.Models
{
public class Product
{
public string Name
{
get;
set;
}
public string Banner
{
get;
set;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Step1.Models
{
public class OrderModel
{
public Customer Customer
{
get;
set;
}
public List<Product> ProductList
{
get;
set;
}
}
}
2 DAL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Step1.DAL;
using Step1.Models;
namespace Step1.DAL
{
public class DBContext
{
public static OrderModel GetOrderList()
{
OrderModel model = new OrderModel();
model.Customer = new Customer() { CustomerID = "10000", CompanyName = "redwave" };
model.ProductList = new List<Product>();
for (int i = 0; i < 10; i++)
{
Product p = new Product();
p.Banner = string.Format("Banner{0}", i.ToString());
p.Name = string.Format("ProductMame{0}", i.ToString());
model.ProductList.Add(p);
}
return model;
}
}
}
3 Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Step1.DAL;
namespace Step1.Controllers
{
public class PartialViewController : Controller
{
//
// GET: /PartialView/
public ActionResult Index()
{
var model= DBContext.GetOrderList();
return View(model);
}
}
}
4 Partial View
@using Step1.Models;
@using System.Collections;
@model IEnumerable<Product>
<table border="1" >
<tr >
<td>
Name
</td>
<td>
Banner
</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@item.Name
</td>
<td>
@item.Banner
</td>
</tr>
}
</table>
5 View
using Step1.Models;
@model OrderModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
<div>
@Model.Customer.CompanyName
</div>
<div>
@Model.Customer.CustomerID
</div>
<div>
@Html.Partial("CustomerListControl",@Model.ProductList)
</div>
</div>
6 項目結構
7 運行結果