在ASP.NET MVC 3中有三种方式从控制器将信息传到视图:
1.强类型的model对象。
2.动态数据类型(用@model dynamic )
3.使用ViewBag
用一个简单的博客例子来对比下动态视图和强类型试图,下面控制器是一个博客列表:
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();
}
}
}
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视图。如下图:
不要勾选Create a strongly-typed view(创建强类型试图)项,创建的视图内容如下:
@{
ViewBag.Title = "IndexNotStonglyTyped";
}
<h2>IndexNotStonglyTyped</h2>
ViewBag.Title = "IndexNotStonglyTyped";
}
<h2>IndexNotStonglyTyped</h2>
在文件“Views\Home\IndexNotStonglyTyped.cshtml”第一行添加model指令和dynamic关键字
@model dynamic
因为是动态视图非强类型视图,没有智能提示。完整的代码:
@model dynamic
@{
ViewBag.Title = "IndexNotStonglyTyped";
}
<h2>Index Not Stongly Typed</h2>
@*此以下代码也要自己手动完成mailto:*@%3Cp%3E <ul>
@foreach (var blog in Model) {
<li>
<a href="@blog.URL">@blog.Name</a>
</li>
}
</ul>
</p>
@{
ViewBag.Title = "IndexNotStonglyTyped";
}
<h2>Index Not Stongly Typed</h2>
@*此以下代码也要自己手动完成mailto:*@%3Cp%3E <ul>
@foreach (var blog in Model) {
<li>
<a href="@blog.URL">@blog.Name</a>
</li>
}
</ul>
</p>
运行的结果:
接下来添加一个强类型视图。把下面的代码添加到controller中:
public ActionResult StonglyTypedIndex() {
return View(topBlogs);
}
return View(topBlogs);
}
注意这里返回对象跟非强类型视图一样都是View(topBlogs)。右击函数StonglyTypedIndex()选择添加视图。勾选Create a
strongly-typed view(创建强类型试图)项,选择模型类下拉列表中Blog 模型。
在这个视图里,Model有智能提示。如图: