动态类型化视图与 强类型化视图

作者 :Rick Anderson

可通过三种方法将信息从控制器传递到 ASP.NET MVC 3 中的视图:

  1. 作为强类型模型对象。
  2. 作为使用动态) 的 @model 动态类型 (
  3. 使用 ViewBag

我编写了一个简单的 MVC 3 热门博客应用程序,用于比较和对比动态视图和强类型视图。 控制器从一个简单的博客列表开始:

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();
        }
    }
}

右键单击 IndexNotStonglyTyped () 方法并添加 Razor 视图。

8475.NotStronglyTypedView[1]

确保未选中 “创建强类型视图 ”框。 生成的视图不包含太多内容:

@{
    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>

6646.NotStronglyTypedView_5F00_IE[1]

现在,我们将添加强类型视图。 将以下代码添加到控制器:

public ActionResult StonglyTypedIndex() {
    return View(topBlogs);
}

请注意,这是完全相同的返回视图 (topBlogs) ;调用 为非强类型视图。 右键单击 StonglyTypedIndex () 并选择“ 添加视图”。 这次选择 Blog Model 类,然后选择 “列表 ”作为基架模板。

5658.StrongView[1]

在新视图模板中,我们获得了 Intellisense 支持。

7002.IntelliSense[1]