動態與 強型別檢視
作者: Rick Anderson
有三種方式可將資訊從控制器傳遞至 ASP.NET MVC 3 中的檢視:
- 做為強型別模型物件。
- 使用動態) @model 作為動態類型 (
- 使用 ViewBag
我撰寫了簡單的 MVC 3 Top Blog 應用程式,以比較和對比動態和強型別檢視。 控制器一開始會以簡單的部落格清單開始:
using System.Collections.Generic;
using System.Web.Mvc;
namespace Mvc3ViewDemo.Controllers {
public class Blog {
public string Name;
public string URL;
}
public class HomeController : Controller {
List<Blog> topBlogs = new List<Blog>
{
new Blog { Name = "ScottGu", URL = "http://weblogs.asp.net/scottgu/"},
new Blog { Name = "Scott Hanselman", URL = "http://www.hanselman.com/blog/"},
new Blog { Name = "Jon Galloway", URL = "http://www.asp.net/mvc"}
};
public ActionResult IndexNotStonglyTyped() {
return View(topBlogs);
}
public ActionResult About() {
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
}
以滑鼠右鍵按一下 IndexNotSificationlyTyped () 方法,然後新增 Razor 檢視。
請確定未核取 [ 建立強型別檢視 ] 方塊。 產生的檢視不包含太多:
@{
ViewBag.Title = "IndexNotStonglyTyped";
}
<h2>IndexNotStonglyTyped</h2>
On the first line of the Views\Home\IndexNotStonglyTyped.cshtml file, add the model directive and the dynamic keyword.
@model dynamic
由於我們使用動態而非強型別檢視,因此 Intellisense 無法協助我們。 完成的程式碼如下所示:
@model dynamic
@{
ViewBag.Title = "IndexNotStonglyTyped";
}
<h2>Index Not Stongly Typed</h2>
<p>
<ul>
@foreach (var blog in Model) {
<li>
<a href="@blog.URL">@blog.Name</a>
</li>
}
</ul>
</p>
現在,我們將新增強型別檢視。 將下列程式碼新增至控制器:
public ActionResult StonglyTypedIndex() {
return View(topBlogs);
}
請注意,它完全相同的傳回 View (topBlogs) ;呼叫 作為非強型別檢視。 以滑鼠右鍵按一下 STypedIndex () 內部,然後選取 [ 新增檢視]。 這次選取 [部落格 模型] 類別,然後選取 [ 清單 ] 作為 Scaffold 範本。
在新檢視範本內,我們會獲得 Intellisense 支援。