在这个Tip中,Stephen Walther向你展示了如何创建一个ASP.NET MVC视图用户控件,它能接受一组数据库记录,并自动在一个HTML表格中呈现这些记录。使用视图用户控件的好处是,你可以自定义特定列的呈现方式。
原文地址:http://weblogs.asp.net/stephenwalther/archive/2008/06/25/asp-net-mvc-tip-9-create-a-gridview-view-user-control.aspx
摘要:在这个Tip中,Stephen Walther向你展示了如何创建一个ASP.NET MVC视图用户控件,它能接受一组数据库记录,并自动在一个HTML表格中呈现这些记录。使用视图用户控件的好处是,你可以自定义特定列的呈现方式。
在昨天的Tip中,我解释了如何创建新的HTML辅助方法来在HTML表中呈现一组数据库记录。换句话说,我展示了一种在ASP.NET MVC中模拟GridView控件的方法。在今天的Tip中,我将继续介绍第二种模拟GridView的方法。
在今天的Tip中,我将解释如何使用ASP.NET MVC视图用户控件来模拟GridView控件。ASP.NET MVC视图用户控件和ASP.NET用户控件类似,但有一个重要的区别。和ASP.NET MVC视图一样,视图用户控件可以接受强类型的视图数据。我们将创建一个接受IEnumerable视图数据的视图用户控件。
清单1中包含了GridView视图用户控件。

清单1 - GridView.ascx

<%
@ Control Language="C#" AutoEventWireup="true" CodeBehind="GridView.ascx.cs" Inherits="Tip9.Views.Home.GridView" %>

<%
@ Import Namespace="System.Reflection" %>

<%
-- Show the Headers --%>
<table class="gridView">
<thead>
<tr>

<%
foreach (PropertyInfo prop in this.Columns)
{ %>
<th><%= prop.Name %></th>

<%
} %>
</tr>
</thead>

<%
-- Show the Rows --%>
<tbody>

<%
foreach (object row in this.Rows)
{ %>
<tr class="<%= this.FlipCssClass( "item", "alternatingItem") %>">

<%
-- Show Each Column --%>

<%
foreach (PropertyInfo prop in this.Columns)
{ %>
<td>

<%
var typeCode = Type.GetTypeCode(prop.PropertyType); %>

<%
-- String Columns --%>

<%
if (typeCode == TypeCode.String)
{ %>
<%= GetColumnValue(row, prop.Name)%>

<%
} %>

<%
-- DateTime Columns --%>

<%
if (typeCode == TypeCode.DateTime)
{ %>
<%= GetColumnValue(row, prop.Name, "{0:D}")%>

<%
} %>

<%
-- Decimal Columns --%>

<%
if (typeCode == TypeCode.Decimal)
{ %>
<%= GetColumnValue(row, prop.Name, "{0:c}") %>

<%
} %>

<%
-- Boolean Columns --%>

<%
if (typeCode == TypeCode.Boolean)
{ %>

<%
if ((bool)(this.GetColumnValue(row, prop.Name)))
{ %>
<input type="checkbox" disabled="disabled" checked="checked" />

<%
}
else
{ %>
<input type="checkbox" disabled="disabled" />

<%
} %>

<%
} %>

<%
-- Integer Columns --%>

<%
if (typeCode == TypeCode.Int32)
{ %>
<%= GetColumnValue(row, prop.Name)%>

<%
} %>
</td>

<%
} %>
</tr>

<%
} %>
</tbody>
</table>
注意GridView.ascx文件包含两个循环。第一个循环遍历了表头,第二个循环遍历表的所有行。
一系列的if语句用于显示特殊的列。根据列的类型——Integer、String、Decimal、DateTime、Boolean——会使用不同的模板显示列中的值。例如,对于Boolean列,会显示一个复选框来标识列的值(如图1)。当然,你可以通过修改HTML来自定义这些列的外观。
图1 - GridView

清单2包含了GridView视图用户控件的code-behind文件。注意视图用户控件拥有一个泛型构造器,可以接受IEnumerable视图数据。它还暴露了很多有用的属性和方法。例如,Columns属性返回数据库表中所有列的信息(该信息是通过反射得到的)。Rows属性返回数据表的所有行。

清单2 - GridView.ascx.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Mvc;
using System.Reflection;
namespace Tip9.Views.Home


{
public partial class GridView : System.Web.Mvc.ViewUserControl<IEnumerable>

{
protected PropertyInfo[] Columns

{
get

{
var e = ViewData.Model.GetEnumerator();
e.MoveNext();
object firstRow = e.Current;
if (firstRow == null)

{
throw new Exception("No data passed to GridView User Control.");
}
return firstRow.GetType().GetProperties();
}
}
protected IEnumerable Rows

{

get
{ return ViewData.Model; }
}
protected object GetColumnValue(object row, string columnName)

{
return DataBinder.Eval(row, columnName);
}
protected object GetColumnValue(object row, string columnName, string format)

{
return DataBinder.Eval(row, columnName, format);
}
bool flip = false;
protected string FlipCssClass(string className, string alternativeClassName)

{
flip = !flip;
return flip ? className : alternativeClassName;
}
}
}
你可以通过调用Html.RenderUserControl()方法在视图页中使用GridView控件。清单3中的视图页呈现了GridView视图用户控件。主页该页面包含一个CSS样式表。该样式表用于自定义GridView所呈现的表格的外观。例如,alternating CSS类用于格式化GridView中的偶数行。

清单3 - Index.aspx (C#)

<%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Tip9.Views.Home.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>Index</title>

<style type="text/css">
.gridView

{
}{
border-collapse: collapse;
}
.gridView th, .gridView td

{
}{
padding: 5px;
}
.gridView th

{
}{
border-bottom: double 3px black;
}
.gridView td

{
}{
border-bottom: solid 1px black;
}
.alternatingItem

{
}{
background-color: lightgrey;
}
</style>
</head>
<body>
<div>
<%= Html.RenderUserControl("~/Views/Home/GridView.ascx", ViewData.Model) %>
</div>
</body>
</html>
视图数据由清单4重的控制器提供。该控制器通过一个LINQ to SQL查询取得数据库数据。然而,GridView可以与通过ADO.NET、NHibernate或其他任何方式获取来的数据完美地兼容。GridView需要的是IEnumerable数据。只要你给GridView传递的是IEnumerable,他就会很happy。

清单4 - HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tip9.Models;
namespace Tip9.Controllers


{
public class HomeController : Controller

{
private MovieDataContext _db = new MovieDataContext();
public ActionResult Index()

{
return View(_db.Movies);
}
}
}
比起昨天的Tip中的方法,我更喜欢今天这种为数据库数据显示表格的方法。于昨天Tip中介绍的方法不同,今天的方法可以完全自定义GridView的外观。
此处下载源代码:http://weblogs.asp.net/blogs/stephenwalther/Downloads/Tip9/Tip9.zip。
-----
广告:http://regex-lib.net/,.NET正则表达式库。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步