Asp.net的优势就在于快速构建应用,而对于一些最基础数据的增删改以及分页事件或者样式的设定可以通过在父类中写上虚方法来供子类调用,如果子类需要在模板的基础上衍生变化或者索性不要父类的方法的话,则只需要重写父类的方法即可。
实验代码如下:
首先是模板类的抽象,继承自Page类;
1 public class Template : System.Web.UI.Page 2 { 3 4 protected override void OnLoad(EventArgs e) 5 { 6 base.OnLoad(e); 7 8 if (!IsPostBack) 9 { 10 DataRefresh(); 11 } 12 } 13 14 protected virtual void DataRefresh() 15 { 16 } 17 18 protected virtual void grid_Init(object sender, EventArgs e) 19 { 20 var grid = sender as GridView; 21 grid.AllowPaging = true; 22 grid.PageSize = 10; 23 grid.PagerSettings.Mode = PagerButtons.NumericFirstLast; 24 } 25 26 protected virtual void grid_PageIndexChanging(object sender, GridViewPageEventArgs e) 27 { 28 var grid = sender as GridView; 29 grid.PageIndex = e.NewPageIndex; 30 DataRefresh(); 31 } 32 }
然后是一个继承此模板类的具体实例;
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Child.aspx.cs" Inherits="WebTest.Child" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8 <title></title> 9 </head> 10 <body> 11 <form id="form1" runat="server"> 12 <div> 13 <asp:GridView ID="grid" runat="server" OnInit="grid_Init" OnPageIndexChanging="grid_PageIndexChanging"></asp:GridView> 14 </div> 15 </form> 16 </body> 17 </html>
最后就是关键的后台代码实现,此处假设需要修改grid的每页显示数和分页样式;
1 public partial class Child : Template 2 { 3 4 protected override void DataRefresh() 5 { 6 grid.DataSource = new LogDao().GetLogsByYearMonth("2012", "10"); 7 grid.DataBind(); 8 } 9 10 protected override void grid_Init(object sender, EventArgs e) 11 { 12 base.grid_Init(sender, e); 13 14 grid.PagerSettings.Mode = PagerButtons.NextPreviousFirstLast; 15 grid.PageSize = 15; 16 } 17 18 }
以上仅是提供一种思路,如有错误望各网友批评指正。
时间: 2024-09-29 16:35:13