Tool:Visual Studio 2013 Ultimate Update 4
OS:Windows 8.1
ASP.NET MVC 5
Partial View是一個可以重複的單位,Partial View可以是強型別的Partial View或Dynamic的。
強型別的Partial View範例如下:
- Model如下:
public class Employee {
public int ID { get; set; }
public string Name { get; set; }
}
}
- HomeController
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
Employee emp = new Employee( ) { ID=1,Name="Mary"};
return View(emp);
}
}
- 強型別的Partial View ,_Partial.cshtml
@model WebApplication3.Models.Employee
<ul>
<li>@Model.ID </li>
<li>@Model.Name </li>
</ul>
- 在Parent View使用Partial View
@model WebApplication3.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@Html.Partial("_Partial")
</div>
</body>
</html>
- Parent View執結果:
- 將強型別Partial View改為dynamic partial View
@model dynamic
<ul>
<li>@Model.ID </li>
<li>@Model.Name </li>
</ul>
Parent View執行結果同上圖。兩者的差別,強型別Partial View是在編譯階段決定型別;而Dynamic Partial View在Runtime才處理。因此,在Partial View中,不能直接將Model拿來使用,需要明確轉型,例如在Partial View中加入以下程式碼:
@model dynamic
<ul>
<li>@Model.ID </li>
<li>@Model.Name </li>
</ul>
@Html.TextBoxFor( m => Model.ID )
@Html.TextBoxFor( m => Model.Name )
Parent View執行結果,將得到以下錯誤訊息:
Compiler Error Message: CS1963: An expression tree may not contain a dynamic operation
修訂程式如下來解決問題:
@model dynamic
<ul>
<li>@Model.ID </li>
<li>@Model.Name </li>
</ul>
@{
WebApplication3.Models.Employee emp = (WebApplication3.Models.Employee )Model;
}
@Html.TextBoxFor( m => emp.ID )
@Html.TextBoxFor( m => emp.Name )
Parent View執行結果:
沒有留言:
張貼留言