三层架构将整个业务应用划分为:(1)界面UI层;(2)业务逻辑层;(3)数据访问层。
对于复杂的系统分层可以让结构更加清晰,模块更加独立,便于维护。
0077.png
各层的任务:
(1)数据访问层:负责数据库的操作。
(2)业务逻辑层:实现功能模块的业务逻辑。
(3)界面UI层:绘制界面,以及负责界面相关代码。
(4)实体类:将数据库中的表转化为面向对象思想中的类。
一、案例需求和资料准备
搜索:
添加学生:
0079.PNG
编辑学生信息:
0080.PNG
统计人数:
0081.PNG
案例需求:使用三层架构实现学生信息管理,包括学生信息搜索,信息新增,信息删除,信息编辑修改等。
资料准备:
--专业分类(1)哲学;(2)经济学;(3)法学;(4)教育学;(5)文学;(6)历史学;(7)理学;(8)工学;(9)农学;(10)医学;(11)军事学;(12)管理学;(13)艺术学
create table MajorType
(
MajorTypeId int primary key identity(1,1), --编号
MajorTypeName varchar(50) not null --专业分类名称
)
insert into MajorType(MajorTypeName) values('工学')
insert into MajorType(MajorTypeName) values('艺术学')
--专业
create table Major
(
MajorId int primary key identity(1,1), --编号
MajorTypeId int not null, --类型编号
MajorName varchar(50) not null --专业名称
)
insert into Major(MajorTypeId,MajorName) values(1,'计算机科学与应用')
insert into Major(MajorTypeId,MajorName) values(1,'建筑学')
insert into Major(MajorTypeId,MajorName) values(2,'美术学')
insert into Major(MajorTypeId,MajorName) values(2,'戏剧与影视学')
--学生
create table Student
(
StudentId int primary key identity(1,1), --编号
MajorId int not null, --专业编号
StudentName varchar(50) not null, --学生姓名
StudentSex varchar(50) not null, --学生性别
StudentPhone varchar(50) not null, --电话
StudentMail varchar(50) not null --邮箱
)
insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail)
values(1,'刘备','男','13554878965','liubei@qq.com')
insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail)
values(1,'关羽','男','15389874521','guanyu@qq.com')
insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail)
values(2,'张飞','男','18987542525','zhangfei@qq.com')
insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail)
values(2,'赵云','男','13696896547','zhaoyun@qq.com')
insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail)
values(3,'黄忠','男','13778777888','huangzhong@qq.com')
insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail)
values(3,'马超','男','13221212325','machao@qq.com')
insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail)
values(4,'魏延','男','13996147455','weiyan@qq.com')
insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail)
values(4,'周仓','男','13437522241','zhoucang@qq.com')
二、项目结构
(1)创建一个空白解决方案。
(2)在解决方案中创建类库项目MyEntity代表"实体类"。
(3)在解决方案中创建类库项目MyDAL代表"数据访问层"。
(4)在解决方案中创建类库项目MyBLL代表"业务逻辑层"。
(5)在解决方案中创建网站程序MyUI代表"界面UI层"。
0012.PNG
三、实体类编写
namespace MyEntity
{
//专业类型
public class MajorTypeEntity
{
public int MajorTypeId { get; set; } //编号
public string MajorTypeName { get; set; }//专业分类名称
}
}
namespace MyEntity
{
//专业
public class MajorEntity
{
public int MajorId { get; set; } //编号
public int MajorTypeId { get; set; } //类型编号
public string MajorName { get; set; } //专业名称
}
}
namespace MyEntity
{
//学生
public class StudentEntity
{
public int StudentId { get; set; } //编号
public int MajorId { get; set; } //专业编号
public string StudentName { get; set; } //学生性别
public string StudentSex { get; set; } //学生性别
public string StudentPhone { get; set; } //学生电话
public string StudentMail { get; set; } //学生邮箱
//添加对象方便查询
public MajorTypeEntity typeEntity { get; set; } //专业类型对象
public MajorEntity majorEntity { get; set; } //专业对象
}
}
四、数据访问层编写
(1)由于数据访问层需要使用实体类,所以需要添加实体类的引用。
即在MyDAL项目上右键-->添加-->引用-->项目,在项目中勾选MyEntity项目。
(2)将之前封装好的DBHelper文件复制到MyDAL项目中,并通过添加现有项,将DBHelper加入项目
备注:DBHelper参照第一章内容
namespace MyDAL
{
public class MajorTypeDAL
{
DBHelper db = new DBHelper();
#region 添加专业类型
public int Add(MajorTypeEntity entity)
{
string sql = "insert into MajorType(MajorTypeName) values(@MajorTypeName)";
db.PrepareSql(sql);
db.SetParameter("MajorTypeName", entity.MajorTypeName);
return db.ExecNonQuery();
}
#endregion
#region 删除专业类型
public int Delete(int MajorTypeId)
{
string sql = "delete from MajorType where MajorTypeId = @MajorTypeId";
db.PrepareSql(sql);
db.SetParameter("MajorTypeId", MajorTypeId);
return db.ExecNonQuery();
}
#endregion
#region 修改专业类型
public int Update(MajorTypeEntity entity)
{
string sql = "update MajorType set MajorTypeName=@MajorTypeName where MajorTypeId=@MajorTypeId";
db.PrepareSql(sql);
db.SetParameter("MajorTypeName", entity.MajorTypeName);
db.SetParameter("MajorTypeId", entity.MajorTypeId);
return db.ExecNonQuery();
}
#endregion
#region 查询所有专业类型
public List<MajorTypeEntity> List()
{
string sql = "select * from MajorType";
db.PrepareSql(sql);
SqlDataReader reader = db.ExecDataReader();
List<MajorTypeEntity> list = new List<MajorTypeEntity>();
while (reader.Read())
{
MajorTypeEntity entity = new MajorTypeEntity();
entity.MajorTypeId = int.Parse(reader["MajorTypeId"].ToString());
entity.MajorTypeName = reader["MajorTypeName"].ToString();
list.Add(entity);
}
reader.Close();
return list;
}
#endregion
#region 查询一个专业类型详情
public MajorTypeEntity Detail(int MajorTypeId)
{
string sql = "select * from MajorType where MajorTypeId=@MajorTypeId";
db.PrepareSql(sql);
db.SetParameter("MajorTypeId", MajorTypeId);
DataTable dt = new DataTable();
dt = db.ExecQuery();
if (dt.Rows.Count == 0)
return null;
MajorTypeEntity entity = new MajorTypeEntity();
entity.MajorTypeId = int.Parse(dt.Rows[0]["MajorTypeId"].ToString());
entity.MajorTypeName = dt.Rows[0]["MajorTypeName"].ToString();
return entity;
}
#endregion
}
}
namespace MyDAL
{
public class MajorDAL
{
DBHelper db = new DBHelper();
#region 添加专业
public int Add(MajorEntity entity)
{
string sql = "insert into Major(MajorTypeId,MajorName) values(@MajorTypeId,@MajorName)";
db.PrepareSql(sql);
db.SetParameter("MajorTypeId", entity.MajorTypeId);
db.SetParameter("MajorName", entity.MajorName);
return db.ExecNonQuery();
}
#endregion
#region 删除专业
public int Delete(int MajorId)
{
string sql = "delete from Major where MajorId = @MajorId";
db.PrepareSql(sql);
db.SetParameter("MajorId", MajorId);
return db.ExecNonQuery();
}
#endregion
#region 修改专业
public int Update(MajorEntity entity)
{
string sql = "update Major set MajorTypeId=@MajorTypeId,MajorName=@MajorName where MajorId=@MajorId";
db.PrepareSql(sql);
db.SetParameter("MajorTypeId", entity.MajorTypeId);
db.SetParameter("MajorName", entity.MajorName);
db.SetParameter("MajorId", entity.MajorId);
return db.ExecNonQuery();
}
#endregion
#region 查询所有专业
public List<MajorEntity> List()
{
string sql = "select * from Major";
db.PrepareSql(sql);
SqlDataReader reader = db.ExecDataReader();
List<MajorEntity> list = new List<MajorEntity>();
while (reader.Read())
{
MajorEntity entity = new MajorEntity();
entity.MajorId = int.Parse(reader["MajorId"].ToString());
entity.MajorTypeId = int.Parse(reader["MajorTypeId"].ToString());
entity.MajorName = reader["MajorName"].ToString();
list.Add(entity);
}
reader.Close();
return list;
}
#endregion
#region 查询一个专业详情
public MajorEntity Detail(int MajorId)
{
string sql = "select * from Major where MajorId=@MajorId";
db.PrepareSql(sql);
db.SetParameter("MajorId", MajorId);
DataTable dt = new DataTable();
dt = db.ExecQuery();
if (dt.Rows.Count == 0)
return null;
MajorEntity entity = new MajorEntity();
entity.MajorId = int.Parse(dt.Rows[0]["MajorId"].ToString());
entity.MajorTypeId = int.Parse(dt.Rows[0]["MajorTypeId"].ToString());
entity.MajorName = dt.Rows[0]["MajorName"].ToString();
return entity;
}
#endregion
}
}
namespace MyDAL
{
public class StudentDAL
{
DBHelper db = new DBHelper();
#region 添加学生
public int Add(StudentEntity entity)
{
string sql = "insert into Student(MajorId,StudentName,StudentSex,StudentPhone,StudentMail) values(@MajorId,@StudentName,@StudentSex,@StudentPhone,@StudentMail)";
db.PrepareSql(sql);
db.SetParameter("MajorId", entity.MajorId);
db.SetParameter("StudentName", entity.StudentName);
db.SetParameter("StudentSex", entity.StudentSex);
db.SetParameter("StudentPhone", entity.StudentPhone);
db.SetParameter("StudentMail", entity.StudentMail);
return db.ExecNonQuery();
}
#endregion
#region 删除学生
public int Delete(int StudentId)
{
string sql = "delete from Student where StudentId = @StudentId";
db.PrepareSql(sql);
db.SetParameter("StudentId", StudentId);
return db.ExecNonQuery();
}
#endregion
#region 修改学生
public int Update(StudentEntity entity)
{
string sql = "update Student set MajorId=@MajorId,StudentName=@StudentName,StudentSex=@StudentSex,StudentPhone=@StudentPhone,StudentMail=@StudentMail where StudentId=@StudentId";
db.PrepareSql(sql);
db.SetParameter("MajorId", entity.MajorId);
db.SetParameter("StudentName", entity.StudentName);
db.SetParameter("StudentSex", entity.StudentSex);
db.SetParameter("StudentPhone", entity.StudentPhone);
db.SetParameter("StudentMail", entity.StudentMail);
db.SetParameter("StudentId", entity.StudentId);
return db.ExecNonQuery();
}
#endregion
#region 查询所有学生
public List<StudentEntity> List()
{
string sql = "select * from Student";
db.PrepareSql(sql);
SqlDataReader reader = db.ExecDataReader();
List<StudentEntity> list = new List<StudentEntity>();
while (reader.Read())
{
StudentEntity entity = new StudentEntity();
entity.StudentId = int.Parse(reader["StudentId"].ToString());
entity.MajorId = int.Parse(reader["MajorId"].ToString());
entity.StudentName = reader["StudentName"].ToString();
entity.StudentSex = reader["StudentSex"].ToString();
entity.StudentPhone = reader["StudentPhone"].ToString();
entity.StudentMail = reader["StudentMail"].ToString();
list.Add(entity);
}
reader.Close();
return list;
}
#endregion
#region 查询一个学生详情
public StudentEntity Detail(int StudentId)
{
string sql = "select * from Student where StudentId=@StudentId";
db.PrepareSql(sql);
db.SetParameter("StudentId", StudentId);
DataTable dt = new DataTable();
dt = db.ExecQuery();
if (dt.Rows.Count == 0)
return null;
StudentEntity entity = new StudentEntity();
entity.StudentId = int.Parse(dt.Rows[0]["StudentId"].ToString());
entity.MajorId = int.Parse(dt.Rows[0]["MajorId"].ToString());
entity.StudentName = dt.Rows[0]["StudentName"].ToString();
entity.StudentSex = dt.Rows[0]["StudentSex"].ToString();
entity.StudentPhone = dt.Rows[0]["StudentPhone"].ToString();
entity.StudentMail = dt.Rows[0]["StudentMail"].ToString();
return entity;
}
#endregion
//--------------------------------------------------------------------------------------------------
#region 搜索学生
public List<StudentEntity> Search(StudentEntity searchEntity,int pageSize, int pageIndex, out int recordCount)
{
//搜索条件处理
string sqlWhere = "";
if (searchEntity.StudentName != null && searchEntity.StudentName.Length != 0)
sqlWhere += " and StudentName like '%" + searchEntity.StudentName + "%'";
//求总记录数量
string sqlCount = "select count(*) from Student left join Major on Student.MajorId = Major.MajorId left join MajorType on Major.MajorTypeId = MajorType.MajorTypeId where 1 = 1 " + sqlWhere;
db.PrepareSql(sqlCount);
recordCount = (int)db.ExecScalar();
//重新计算pageIndex
pageIndex = PageHelper.ComputeCurrPage(pageIndex, pageSize, recordCount);
string sql = "select * from (select ROW_NUMBER() over(order by StudentId desc) RowId,Student.*,Major.MajorTypeId,Major.MajorName,MajorType.MajorTypeName from Student left join Major on Student.MajorId = Major.MajorId left join MajorType on Major.MajorTypeId = MajorType.MajorTypeId where 1 = 1 "+sqlWhere+") Temp where RowId between @Start and @End ";
db.PrepareSql(sql);
db.SetParameter("Start", (pageIndex - 1) * pageSize + 1);
db.SetParameter("End", pageIndex * pageSize);
SqlDataReader reader = db.ExecDataReader();
List<StudentEntity> list = new List<StudentEntity>();
while (reader.Read())
{
StudentEntity entity = new StudentEntity();
entity.StudentId = int.Parse(reader["StudentId"].ToString());
entity.MajorId = int.Parse(reader["MajorId"].ToString());
entity.StudentName = reader["StudentName"].ToString();
entity.StudentSex = reader["StudentSex"].ToString();
entity.StudentPhone = reader["StudentPhone"].ToString();
entity.StudentMail = reader["StudentMail"].ToString();
entity.majorEntity = new MajorEntity();
entity.majorEntity.MajorId = int.Parse(reader["MajorId"].ToString());
entity.majorEntity.MajorName = reader["MajorName"].ToString();
entity.majorEntity.MajorTypeId = int.Parse(reader["MajorTypeId"].ToString());
entity.typeEntity = new MajorTypeEntity();
entity.typeEntity.MajorTypeId = int.Parse(reader["MajorTypeId"].ToString());
entity.typeEntity.MajorTypeName = reader["MajorTypeName"].ToString();
list.Add(entity);
}
reader.Close();
return list;
}
#endregion
#region 根据专业类型分组统计学生人数
public List<object> GetCountByType()
{
string sql = "select MajorTypeName,COUNT(*) StuCount from Student ";
sql += " left join Major on Student.MajorId = Major.MajorId ";
sql += " left join MajorType on Major.MajorTypeId = MajorType.MajorTypeId ";
sql += " group by MajorType.MajorTypeId,MajorTypeName ";
db.PrepareSql(sql);
DataTable dt = new DataTable();
dt = db.ExecQuery();
List<object> list = new List<object>();
foreach (DataRow dr in dt.Rows)
{
var obj = new { TypeName = dr["MajorTypeName"].ToString(), StuCount = dr["StuCount"].ToString() };
list.Add(obj);
}
return list;
}
#endregion
}
}
数据访问层添加了一个工具PageHelper辅助分页功能,此工具也可以单独建立项目来实现。
namespace MyDAL
{
/// <summary>
///PageHelper 的摘要说明
/// </summary>
public class PageHelper
{
#region 计算总页数
public static int GetTotalPage(int totalRecord, int pageSize)
{
int totalPage = 0;
if (totalRecord % pageSize == 0)
totalPage = totalRecord / pageSize;
else
totalPage = totalRecord / pageSize + 1;
return totalPage;
}
#endregion
#region 计算当前页
public static int ComputeCurrPage(int currPage, int totalPage)
{
if (currPage < 1)
currPage = 1;
if (currPage > totalPage)
currPage = totalPage;
return currPage;
}
public static int ComputeCurrPage(int pageIndex, int pageSize, int recordCount)
{
int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1;
if (pageIndex < 1)
pageIndex = 1;
if (pageIndex > pageCount)
pageIndex = pageCount;
return pageIndex;
}
#endregion
}
}
五、业务逻辑层编写
(1)由于业务逻辑层需要使用实体类,所以需要添加实体类的引用。
即在MyBLL项目上右键-->添加-->引用-->项目,在项目中勾选MyEntity项目。
(2)由于业务逻辑层需要调用数据访问层,所以需要添加数据访问层的引用。
即在MyBLL项目上右键-->添加-->引用-->项目,在项目中勾选MyDAL项目。
namespace MyBLL
{
public class MajorTypeBLL
{
MajorTypeDAL dal = new MajorTypeDAL();
#region 添加专业类型
public int Add(MajorTypeEntity entity)
{
return dal.Add(entity);
}
#endregion
#region 删除专业类型
public int Delete(int MajorTypeId)
{
return dal.Delete(MajorTypeId);
}
#endregion
#region 修改专业类型
public int Update(MajorTypeEntity entity)
{
return dal.Update(entity);
}
#endregion
#region 查询所有专业类型
public List<MajorTypeEntity> List()
{
return dal.List();
}
#endregion
#region 查询一个专业类型详情
public MajorTypeEntity Detail(int MajorTypeId)
{
return dal.Detail(MajorTypeId);
}
#endregion
}
}
namespace MyBLL
{
public class MajorBLL
{
MajorDAL dal = new MajorDAL();
#region 添加专业
public int Add(MajorEntity entity)
{
return dal.Add(entity);
}
#endregion
#region 删除专业
public int Delete(int MajorId)
{
return dal.Delete(MajorId);
}
#endregion
#region 修改专业
public int Update(MajorEntity entity)
{
return dal.Update(entity);
}
#endregion
#region 查询所有专业
public List<MajorEntity> List()
{
return dal.List();
}
#endregion
#region 查询一个专业详情
public MajorEntity Detail(int MajorId)
{
return dal.Detail(MajorId);
}
#endregion
}
}
namespace MyBLL
{
public class StudentBLL
{
StudentDAL dal = new StudentDAL();
#region 添加学生
public int Add(StudentEntity entity)
{
return dal.Add(entity);
}
#endregion
#region 删除学生
public int Delete(int StudentId)
{
return dal.Delete(StudentId);
}
#endregion
#region 修改学生
public int Update(StudentEntity entity)
{
return dal.Update(entity);
}
#endregion
#region 查询所有学生
public List<StudentEntity> List()
{
return dal.List();
}
#endregion
#region 查询一个学生详情
public StudentEntity Detail(int StudentId)
{
return dal.Detail(StudentId);
}
#endregion
//----------------------------------------------------------------
#region 搜索学生
public List<StudentEntity> Search(StudentEntity searchEntity, int pageSize, int pageIndex, out int recordCount)
{
return dal.Search(searchEntity, pageSize, pageIndex, out recordCount);
}
#endregion
#region 根据专业类型分组统计学生人数
public List<object> GetCountByType()
{
return dal.GetCountByType();
}
#endregion
}
}
六、界面UI层编写
(1)由于界面UI层需要使用实体类,所以需要添加实体类的引用。
即在MyUI项目上右键-->添加-->引用-->项目,在项目中勾选MyEntity项目。
(2)由于界面UI层需要调用业务逻辑层,所以需要添加业务逻辑层的引用。
即在MyUI项目上右键-->添加-->引用-->项目,在项目中勾选MyBLL项目。
学生搜索查询及删除代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>首页-学生列表</title>
<style type="text/css">
#search{ text-align:center; height:30px; line-height:30px;}
#mylist table{ margin:10px auto;}
</style>
<link href="reveal/reveal.css" rel="stylesheet" type="text/css" />
<script src="reveal/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="reveal/jquery.reveal.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(".update").click(function () {
//alert(this.id);
$("#EditFrame").attr("src", "Update.aspx?StudentId=" + this.id.split("_")[1]);
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="search">
请输入姓名:<asp:TextBox ID="key" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Button ID="btSearch" runat="server" Text="立即搜索" onclick="btSearch_Click" />
<a href="#" data-reveal-id="AddModal" data-animation="none">添加学生</a>
<a href="Group.aspx" target="_blank">统计人数</a>
</div>
<div id="mylist">
<asp:GridView ID="gvStudent" runat="server" DataKeyNames="StudentId" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" Width="912px"
onrowdeleting="gvStudent_RowDeleting">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="typeEntity.MajorTypeName" HeaderText="专业类型" />
<asp:BoundField DataField="majorEntity.MajorName" HeaderText="专业名称" />
<asp:BoundField DataField="StudentName" HeaderText="学生姓名" />
<asp:BoundField DataField="StudentSex" HeaderText="学生性别" />
<asp:BoundField DataField="StudentPhone" HeaderText="电话" />
<asp:BoundField DataField="StudentMail" HeaderText="邮箱" />
<asp:TemplateField>
<HeaderTemplate>操作</HeaderTemplate>
<ItemTemplate>
<a href="#" data-reveal-id="EditModal" data-animation="none" class="update" id="a_<%#Eval("StudentId")%>">编辑</a>
<asp:LinkButton ID="lbDelete" runat="server" CommandName="delete" OnClientClick="return confirm('确定要删除吗?');">删除</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</div>
<div>
<uc1:NumPage ID="MyPage" runat="server" OnPageIndexChanged="MyPage_PageIndexChanged" />
</div>
</form>
</body>
</html>
<%--由于插件样式表中left:50%,所以将margin-left设置成width的一半实现居中--%>
<div id="AddModal" class="reveal-modal" style=" width:520px; margin-left:-260px; height:320px;">
<iframe src="Add.aspx" frameborder="0" width="520" height="320"></iframe>
<a class="close-reveal-modal">×</a>
</div>
<div id="EditModal" class="reveal-modal" style=" width:520px; margin-left:-260px; height:320px;">
<iframe src="" frameborder="0" width="520" height="320" id="EditFrame"></iframe>
<a class="close-reveal-modal">×</a>
</div>
其中使用了Jquery和reveal插件,插件见实际项目。
namespace MyUI
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
#region 绑定数据到控件
private void BindData()
{
//计算当前页
int PageIndex = this.MyPage.GetPageIndex();
//页码大小
int PageSize = 3;
//设置搜索条件给数据查询
StudentEntity entity = new StudentEntity();
entity.StudentName = this.key.Text;
StudentBLL bll = new StudentBLL();
int RecordCount = 0;
List<StudentEntity> list = new List<StudentEntity>();
list = bll.Search(entity, PageSize, PageIndex, out RecordCount);
//绑定数据到控件
this.gvStudent.DataSource = list;
this.gvStudent.DataBind();
//显示分页控件
this.MyPage.ShowControl(PageSize, RecordCount);
}
#endregion
protected void btSearch_Click(object sender, EventArgs e)
{
this.MyPage.SetPageIndex(1);
BindData();
}
#region 删除学生信息
protected void gvStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
StudentBLL bll = new StudentBLL();
bll.Delete(int.Parse(e.Keys["StudentId"].ToString()));
BindData();
}
#endregion
#region 分页
protected void MyPage_PageIndexChanged(object sender, EventArgs e)
{
BindData();
}
#endregion
}
}
学生新增代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>添加学生</title>
<style type="text/css">
body,div{ margin:0px; padding:0px;}
#addTitle{ font-size:16px; font-weight:bold; text-align:center; background-color:#f3f3f3; height:30px; line-height:30px;}
#myTable{ width:500px; margin:10px auto;}
#myTable td{ height:30px; line-height:30px;}
.lefttd{ width:100px; text-align:right;}
.rightrd{ width:400px; text-align:left;}
.errInfo{ color:Red;}
</style>
<script src="jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var jsonType = <%=ViewState["listType"] %>;
var jsonMajor = <%=ViewState["listMajor"]%>;
//绑定专业类型
function BindType()
{
$("#ddlType").append("<option value=''>--请选择--</option>");
for(var i = 0;i< jsonType.length;i++)
{
$("#ddlType").append("<option value='"+jsonType[i].MajorTypeId+"'>"+jsonType[i].MajorTypeName+"</option>");
}
}
//绑定专业
function BindMajor()
{
$("#ddlMajor").append("<option value=''>--请选择--</option>");
}
//检查专业类型
function CheckType()
{
if($("#ddlType").val() == "")
{
$("#spanType").html("请选择专业类型");
return false;
}
else
{
$("#spanType").html("");
return true;
}
}
//检查专业
function CheckMajor()
{
if($("#ddlMajor").val() == "")
{
$("#spanMajor").html("请选择专业类型");
return false;
}
else
{
$("#spanMajor").html("");
return true;
}
}
//检查姓名
function CheckName()
{
if($("#txtName").val() == "")
{
$("#spanName").html("姓名不能为空");
return false;
}
else
{
$("#spanName").html("");
return true;
}
}
//检查性别
function CheckSex()
{
if($(":checked[name=sex]").length == 0)
{
$("#spanSex").html("性别不能为空");
return false;
}
else
{
$("#spanSex").html("");
return true;
}
}
//检查电话
function CheckPhone()
{
var exp = /^(13|15|18)\d{9}$/;
if(!exp.test($("#txtPhone").val()))
{
$("#spanPhone").html("手机号码为空或者格式不正确");
return false;
}
else
{
$("#spanPhone").html("");
return true;
}
}
//检查邮箱
function CheckMail()
{
var exp = /^\w+@\w+(\.[a-zA-Z]{2,3}){1,2}$/;
if(!exp.test($("#txtMail").val()))
{
$("#spanMail").html("邮箱为空或者格式不正确");
return false;
}
else
{
$("#spanMail").html("");
return true;
}
}
$(function(){
BindType();
BindMajor();
//选择专业类型的时候切换专业
$("#ddlType").change(function(){
$("#ddlMajor").html("");
$("#ddlMajor").append("<option value=''>--请选择--</option>");
if($("#ddlType").val() == "")
return;
for(var i = 0;i< jsonMajor.length;i++)
{
if(jsonMajor[i].MajorTypeId == $("#ddlType").val())
$("#ddlMajor").append("<option value='"+jsonMajor[i].MajorId+"'>"+jsonMajor[i].MajorName+"</option>");
}
})
//表单提交验证
$("#form1").submit(function(){
if(CheckType()==true & CheckMajor()==true & CheckName()==true & CheckSex()==true &
CheckPhone() == true & CheckMail() == true)
{
return true;
}
else
{
return false;
}
})
$("#ddlType").blur(function(){
CheckType();
})
$("#ddlMajor").blur(function(){
CheckMajor();
})
$("#txtName").blur(function(){
CheckName();
})
$("[name=sex]").blur(function(){
CheckSex();
})
$("#txtPhone").blur(function(){
CheckPhone();
})
$("#txtMail").blur(function(){
CheckMail();
})
})
</script>
</head>
<body>
<form id="form1" runat="server" clientidmode="Static">
<div>
<div id="addTitle">添加学生信息</div>
<table id="myTable">
<tr>
<td class="lefttd">专业类型:</td>
<td class="rightrd">
<asp:DropDownList ID="ddlType" runat="server" ClientIDMode="Static">
</asp:DropDownList>
<span id="spanType" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">专业:</td>
<td class="rightrd">
<asp:DropDownList ID="ddlMajor" runat="server" ClientIDMode="Static">
</asp:DropDownList>
<span id="spanMajor" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">姓名:</td>
<td class="rightrd">
<asp:TextBox ID="txtName" runat="server" ClientIDMode="Static"></asp:TextBox>
<span id="spanName" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">性别:</td>
<td class="rightrd">
<asp:RadioButton ID="rbBoy" runat="server" Text="男" Checked="false" GroupName="sex" ClientIDMode="Static" />
<asp:RadioButton ID="rbGirl" runat="server" Text="女" Checked="false" GroupName="sex" ClientIDMode="Static" />
<span id="spanSex" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">电话:</td>
<td class="rightrd">
<asp:TextBox ID="txtPhone" runat="server" ClientIDMode="Static"></asp:TextBox>
<span id="spanPhone" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">邮箱:</td>
<td class="rightrd">
<asp:TextBox ID="txtMail" runat="server" ClientIDMode="Static"></asp:TextBox>
<span id="spanMail" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd"> </td>
<td class="rightrd">
<asp:Button ID="btAdd" runat="server" ClientIDMode="Static" Text="添加学生" onclick="btAdd_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
namespace MyUI
{
public partial class Add : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
#region 绑定类型和专业
private void BindData()
{
List<MajorTypeEntity> listType = new List<MajorTypeEntity>();
MajorTypeBLL typeBll = new MajorTypeBLL();
listType = typeBll.List();
ViewState["listType"] = MyJson.ToJsJson(listType);
List<MajorEntity> listMajor = new List<MajorEntity>();
MajorBLL majorBll = new MajorBLL();
listMajor = majorBll.List();
ViewState["listMajor"] = MyJson.ToJsJson(listMajor);
}
#endregion
#region 添加学生信息
protected void btAdd_Click(object sender, EventArgs e)
{
StudentBLL bll = new StudentBLL();
StudentEntity entity = new StudentEntity();
entity.MajorId = int.Parse(Request["ddlMajor"]);
entity.StudentName = this.txtName.Text;
entity.StudentSex = this.rbBoy.Checked == true ? "男" : "女";
entity.StudentPhone = this.txtPhone.Text;
entity.StudentMail = this.txtMail.Text;
bll.Add(entity);
Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('添加成功');window.parent.location.reload();</script>");
}
#endregion
}
}
学生编辑修改代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>修改学生</title>
<style type="text/css">
body,div{ margin:0px; padding:0px;}
#addTitle{ font-size:16px; font-weight:bold; text-align:center; background-color:#f3f3f3; height:30px; line-height:30px;}
#myTable{ width:500px; margin:10px auto;}
#myTable td{ height:30px; line-height:30px;}
.lefttd{ width:100px; text-align:right;}
.rightrd{ width:400px; text-align:left;}
.errInfo{ color:Red;}
</style>
<script src="jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var jsonType = <%=ViewState["listType"] %>;
var jsonMajor = <%=ViewState["listMajor"]%>;
//检查专业类型
function CheckType()
{
if($("#ddlType").val() == "")
{
$("#spanType").html("请选择专业类型");
return false;
}
else
{
$("#spanType").html("");
return true;
}
}
//检查专业
function CheckMajor()
{
if($("#ddlMajor").val() == "")
{
$("#spanMajor").html("请选择专业类型");
return false;
}
else
{
$("#spanMajor").html("");
return true;
}
}
//检查姓名
function CheckName()
{
if($("#txtName").val() == "")
{
$("#spanName").html("姓名不能为空");
return false;
}
else
{
$("#spanName").html("");
return true;
}
}
//检查性别
function CheckSex()
{
if($(":checked[name=sex]").length == 0)
{
$("#spanSex").html("性别不能为空");
return false;
}
else
{
$("#spanSex").html("");
return true;
}
}
//检查电话
function CheckPhone()
{
var exp = /^(13|15|18)\d{9}$/;
if(!exp.test($("#txtPhone").val()))
{
$("#spanPhone").html("手机号码为空或者格式不正确");
return false;
}
else
{
$("#spanPhone").html("");
return true;
}
}
//检查邮箱
function CheckMail()
{
var exp = /^\w+@\w+(\.[a-zA-Z]{2,3}){1,2}$/;
if(!exp.test($("#txtMail").val()))
{
$("#spanMail").html("邮箱为空或者格式不正确");
return false;
}
else
{
$("#spanMail").html("");
return true;
}
}
$(function(){
$("#ddlType").change(function(){
$("#ddlMajor").html("");
$("#ddlMajor").append("<option value=''>--请选择--</option>");
if($("#ddlType").val() == "")
return;
for(var i = 0;i< jsonMajor.length;i++)
{
if(jsonMajor[i].MajorTypeId == $("#ddlType").val())
$("#ddlMajor").append("<option value='"+jsonMajor[i].MajorId+"'>"+jsonMajor[i].MajorName+"</option>");
}
})
//表单提交验证
$("#form1").submit(function(){
if(CheckType()==true & CheckMajor()==true & CheckName()==true & CheckSex()==true &
CheckPhone() == true & CheckMail() == true)
{
return true;
}
else
{
return false;
}
})
$("#ddlType").blur(function(){
CheckType();
})
$("#ddlMajor").blur(function(){
CheckMajor();
})
$("#txtName").blur(function(){
CheckName();
})
$("[name=sex]").blur(function(){
CheckSex();
})
$("#txtPhone").blur(function(){
CheckPhone();
})
$("#txtMail").blur(function(){
CheckMail();
})
})
</script>
</head>
<body>
<form id="form1" runat="server" clientidmode="Static">
<div>
<div id="addTitle">添加学生信息</div>
<table id="myTable">
<tr>
<td class="lefttd">专业类型:</td>
<td class="rightrd">
<asp:DropDownList ID="ddlType" runat="server" ClientIDMode="Static">
</asp:DropDownList>
<span id="spanType" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">专业:</td>
<td class="rightrd">
<asp:DropDownList ID="ddlMajor" runat="server" ClientIDMode="Static">
</asp:DropDownList>
<span id="spanMajor" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">姓名:</td>
<td class="rightrd">
<asp:TextBox ID="txtName" runat="server" ClientIDMode="Static"></asp:TextBox>
<span id="spanName" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">性别:</td>
<td class="rightrd">
<asp:RadioButton ID="rbBoy" runat="server" Text="男" Checked="false" GroupName="sex" ClientIDMode="Static" />
<asp:RadioButton ID="rbGirl" runat="server" Text="女" Checked="false" GroupName="sex" ClientIDMode="Static" />
<span id="spanSex" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">电话:</td>
<td class="rightrd">
<asp:TextBox ID="txtPhone" runat="server" ClientIDMode="Static"></asp:TextBox>
<span id="spanPhone" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd">邮箱:</td>
<td class="rightrd">
<asp:TextBox ID="txtMail" runat="server" ClientIDMode="Static"></asp:TextBox>
<span id="spanMail" class="errInfo"></span>
</td>
</tr>
<tr>
<td class="lefttd"> </td>
<td class="rightrd">
<asp:Button ID="btUpdate" runat="server" ClientIDMode="Static" Text="修改学生"
onclick="btUpdate_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
namespace MyUI
{
public partial class Update : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
#region 学生信息
private void BindData()
{
//获取学生详情
StudentEntity stuEntity = new StudentEntity();
StudentBLL stuBll = new StudentBLL();
stuEntity = stuBll.Detail(int.Parse(Request["StudentId"].ToString()));
if (stuEntity == null)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('找不到该学生信息');window.parent.location.reload();</script>");
return;
}
//通过学生信息获取专业信息,从专业信息中才能获取专业类型编号,因为学生表中没有专业类型编号
MajorEntity majorEntity = new MajorEntity();
MajorBLL majorBll = new MajorBLL();
majorEntity = majorBll.Detail(stuEntity.MajorId);
//绑定专业类型下拉框
List<MajorTypeEntity> listType = new List<MajorTypeEntity>();
MajorTypeBLL typeBll = new MajorTypeBLL();
listType = typeBll.List();
this.ddlType.DataSource = listType;
this.ddlType.DataValueField = "MajorTypeId";
this.ddlType.DataTextField = "MajorTypeName";
this.ddlType.DataBind();
this.ddlType.Items.Insert(0, new ListItem("--请选择--", ""));
this.ddlType.SelectedValue = majorEntity.MajorTypeId.ToString();
ViewState["listType"] = MyJson.ToJsJson(listType);
//绑定专业下拉框
List<MajorEntity> listMajor = new List<MajorEntity>();
listMajor = majorBll.List();
ViewState["listMajor"] = MyJson.ToJsJson(listMajor);
listMajor = listMajor.Where(p=>p.MajorTypeId == majorEntity.MajorTypeId).ToList();
this.ddlMajor.DataSource = listMajor;
this.ddlMajor.DataValueField = "MajorId";
this.ddlMajor.DataTextField = "MajorName";
this.ddlMajor.DataBind();
this.ddlMajor.Items.Insert(0, new ListItem("--请选择--", ""));
this.ddlMajor.SelectedValue = stuEntity.MajorId.ToString();
//绑定表单其它元素
this.txtName.Text = stuEntity.StudentName;
this.txtPhone.Text = stuEntity.StudentPhone;
this.txtMail.Text = stuEntity.StudentMail;
if (stuEntity.StudentSex.Equals("男")) this.rbBoy.Checked = true;
if (stuEntity.StudentSex.Equals("女")) this.rbGirl.Checked = true;
}
#endregion
#region 修改学生信息
protected void btUpdate_Click(object sender, EventArgs e)
{
StudentEntity entity = new StudentEntity();
StudentBLL bll = new StudentBLL();
entity = bll.Detail(int.Parse(Request["StudentId"].ToString()));
if (entity == null)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('找不到该学生信息');window.parent.location.reload();</script>");
return;
}
entity.MajorId = int.Parse(this.ddlMajor.SelectedValue.ToString());
entity.StudentName = this.txtName.Text;
entity.StudentSex = this.rbBoy.Checked == true ? "男" : "女";
entity.StudentPhone = this.txtPhone.Text;
entity.StudentMail = this.txtMail.Text;
bll.Update(entity);
Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('修改成功');window.parent.location.reload();</script>");
}
#endregion
}
}
扩展:按照专业类型统计学生人数
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvGroup" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="专业类型" DataField="TypeName" />
<asp:BoundField HeaderText="学生人数" DataField="StuCount" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
namespace MyUI
{
public partial class Group : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
#region 绑定数据
private void BindData()
{
List<object> list = new List<object>();
StudentBLL bll = new StudentBLL();
list = bll.GetCountByType();
this.gvGroup.DataSource = list;
this.gvGroup.DataBind();
}
#endregion
}
}
网友评论