用类的继承关系(重写父类的方法)实现简易后台代码模板
2024-07-10 12:41:00
供稿:网友
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;
}
}
以上仅是提供一种思路,如有错误望各网友批评指正。