[翻译] ASP.NET MVC Tip #9 – 创建GridView视图用户控件

本文介绍如何在ASP.NET MVC中创建一个视图用户控件,模仿GridView控件的功能,自定义显示数据库记录,包括表头、行及列的渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址: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正则表达式库。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值