Asp.net的優勢就在於快速構建應用,而對於一些最基礎數據的增刪改以及分頁事件或者樣式的設定可以通過在父類中寫上虛方法來供子類調用,如果子類需要在模板的基礎上衍生變化或者索性不要父類的方法的話,則只需要重寫父類的方法即可。
實驗代碼如下:
首先是模板類的抽象,繼承自Page類;
復制代碼 代碼如下:
public class Template : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
DataRefresh();
}
}
protected virtual void DataRefresh()
{
}
protected virtual void grid_Init(object sender, EventArgs e)
{
var grid = sender as GridView;
grid.AllowPaging = true;
grid.PageSize = 10;
grid.PagerSettings.Mode = PagerButtons.NumericFirstLast;
}
protected virtual void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
var grid = sender as GridView;
grid.PageIndex = e.NewPageIndex;
DataRefresh();
}
}
然後是一個繼承此模板類的具體實例;
復制代碼 代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Child.aspx.cs" Inherits="WebTest.Child" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grid" runat="server" OnInit="grid_Init" OnPageIndexChanging="grid_PageIndexChanging"></asp:GridView>
</div>
</form>
</body>
</html>
最後就是關鍵的後台代碼實現,此處假設需要修改grid的每頁顯示數和分頁樣式;
復制代碼 代碼如下:
public partial class Child : Template
{
protected override void DataRefresh()
{
grid.DataSource = new LogDao().GetLogsByYearMonth("2012", "10");
grid.DataBind();
}
protected override void grid_Init(object sender, EventArgs e)
{
base.grid_Init(sender, e);
grid.PagerSettings.Mode = PagerButtons.NextPreviousFirstLast;
grid.PageSize = 15;
}
}
以上僅是提供一種思路,如有錯誤望各網友批評指正。