五、 成功通过单元测试
在改变了ForumRepository和ForumController类之后,我们的新的单元测试成功通过!现在,我们的论坛应用程序共有5个单元测试
六、 创建视图
严格地说,目前为止,还不存在什么真正的为我们的论坛应用程序创建视图的任何理由。我们不需要实际地运行应用程序来确保应用程序正常工作。执行我们的单元测试可以比仅用肉眼观察能够提供更有力的证明证实应用程序正确工作。
然而,我也是一个人。我也喜欢偶尔运行一下应用程序,仅仅是为了达到检查程序是否能够正常运行的目的。因此,我创建了两个相应于Index()动作和Thread()动作的简单的视图。
其中,Index()动作相应的视图包含于列表4中。这个视图简单地以一个列表的方式显示所有的线程
列表4—Views\Forum\Index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcForums.Views.Forum.Index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<div>
<ul>
<% foreach (var m in ViewData.Model)
{ %>
<li>
<%= Html.Encode(m.Author) %>
<%= Html.ActionLink(m.Subject, "Thread", new {threadId=m.Id})%>
</li>
<% } %>
</ul>
</div>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<div>
<ul>
<% foreach (var m in ViewData.Model)
{ %>
<li>
<%= Html.Encode(m.Author) %>
<%= Html.ActionLink(m.Subject, "Thread", new {threadId=m.Id})%>
</li>
<% } %>
</ul>
</div>
</body>
</html>
Index视图实现针对每一个线程生成一个超级链接。如果你点击一个超级链接,你便被导航到线程视图。列表5给出了这个线程视图的完整代码,此视图负责在一个特定的线程中显示所有的信息。
列表5—Views\Forum\Thread.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Thread.aspx.cs" Inherits="MvcForums.Views.Forum.Thread" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<div>
<ul>
<% foreach (var m in ViewData.Model)
{ %>
<li>
<%= Html.Encode(m.Author) %>
<%= Html.Encode(m.Subject) %>
<p>
<%= Html.Encode(m.Body) %>
</p>
</li>
<% } %>
</ul>
</div>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<div>
<ul>
<% foreach (var m in ViewData.Model)
{ %>
<li>
<%= Html.Encode(m.Author) %>
<%= Html.Encode(m.Subject) %>
<p>
<%= Html.Encode(m.Body) %>
</p>
</li>
<% } %>
</ul>
</div>
</body>
</html>
请注意,Index和Thread这两个视图都是强类型化的。如果你观察一下无论哪一个视图的code-behind文件,你都会注意到这些视图都会以强类型化的方式把ViewData.Model属性转换成一个List<Movie>集合的实例。例如,下面的列表6就提供了Index视图对应的code-behind文件定义。
列表6—Views\Forums\index.aspx.cs
using System.Collections.Generic;
using System.Web.Mvc;
using MvcForums.Models;
namespace MvcForums.Views.Forum
{
public partial class Index : ViewPage<List<Message>>
{
}
}
using System.Web.Mvc;
using MvcForums.Models;
namespace MvcForums.Views.Forum
{
public partial class Index : ViewPage<List<Message>>
{
}
}