步骤 5 创建视图
我们将鼠标移到Index 这个方法上,然后右击鼠标,在弹出的菜单中选择“增加视图”,这就会显示如下图的菜单,我们保持视图的名为Index不变,但选择”创建强类型视图”的复选框,并且在下拉框中选择Web.Models.Product作为返回填充的模型类。然后点“选择master模版页”的复选框,选/Views/Shared/Site.Master作为我们的模版页。
完成后,会在Views目录下多了一个名为Products的子目录和一个Index.aspx 的文件。打开Index.aspx文件的代码,观察@Page的部分,由于我们是要在页面中获得产品记录的一个集合再呈现出来,因此需要这里修改一下,修改为:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Web.Models.Product>>" %>
接下来的工作就简单了,我们就设计HTML的表格头,如下所示:
<table class="grid">
<tr>
<th>Product</th>
<th>Category</th>
<th>Qty/Unit</th>
<th>Price</th>
<th>Discontinued</th>
</tr>
<tr>
<th>Product</th>
<th>Category</th>
<th>Qty/Unit</th>
<th>Price</th>
<th>Discontinued</th>
</tr>
接下来就是遍历获得的数据集合了,可以使用foreach去实现。其中注意学习String.Format的用法,它在这里格式化了单价,而对于如果产品没折扣的话则,折扣列不显示任何东西,而如果是有折扣的话则显示一张小图片。
最后,我们通过www.yoursite.com/Products 或者www.yoursite.com/Products/Index就可以看到我们简单的从数据库表中展示的数据记录了。
<% foreach (var item in Model) { %>
<tr>
<td class="left"><%: item.ProductName %></td>
<td class="left"><%: item.Category.CategoryName %></td>
<td class="left"><%: item.QuantityPerUnit %></td>
<td class="right"><%: String.Format("{0:C}", item.UnitPrice) %></td>
<td>
<% if (item.Discontinued) { %>
<img src="<%=Url.Content("~/Content/cancel.png") %>" alt="Discontinued" title="Discontinued" />
<% } %>
</td>
</tr>
<% } %>
<tr>
<td class="left"><%: item.ProductName %></td>
<td class="left"><%: item.Category.CategoryName %></td>
<td class="left"><%: item.QuantityPerUnit %></td>
<td class="right"><%: String.Format("{0:C}", item.UnitPrice) %></td>
<td>
<% if (item.Discontinued) { %>
<img src="<%=Url.Content("~/Content/cancel.png") %>" alt="Discontinued" title="Discontinued" />
<% } %>
</td>
</tr>
<% } %>
在接下来的几讲中,将会教大家如何对表格功能进行优化,比如增加排序,分页,筛选等功能,请密切期待。