在《【ASP.NET】利用Repeater完成对SQL Server数据库的增删改查》(点击打开链接)展示了如果纯粹地利用ASP.NET完成对SQL Server的增删改查操作,但是,缺点很明显,原本简单的网页编程引入了许多ASP.NET独有的概念,并且所有增删改查的处理停留在一个页面不易维护,最重要的是,大量使用服务器组件,注定导致网页的加载与处理的速度下降。
还是同一个功能,对数据库某张表进行增删改查,只是下面提供另一个方案完成ASP.NET对数据库的增删改查,就是Repeater仅作为一个foreach的遍历器来使用,其余部分完全使用客户端组件来实现。
而数据的处理全部利用《【ASP.NET】利用jQuery与.ashx完成简单的Ajax》(点击打开链接)中的形式,先将数据以表单或者Ajax提交到.ashx文件中,处理完再重定向会主页面,并且以Session的形式传回提示信息,提示信息一显示则销毁这个Session,以此说明在.ashx使用Session。
首先,解决方案的目录结构如下图所示:
数据库查询类DB.cs不用说了,这个文件,在我之前的文章出现多次了,具体可以看《【C#】利用C#窗体与SQL Server的连接、Treeview制作SQL Server数据库查看器》(点击打开链接),代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;//DataTable用到
using System.Data.SqlClient;//一系列的数据库操作类用到
using System.Configuration;
namespace RepeaterAjax
{
class DB : IDisposable
{
private SqlConnection sqlConnection;
// 以下代码,保证该类只能有一个实例
// 在自己内部定义自己的一个实例,只供内部调用
private static DB db = null;
// 这个类必须自动向整个系统提供这个实例对象
// 这里提供了一个供外部访问本class的静态方法,可以直接访问
public static DB getInstance()
{
if (db == null)
{
db = new DB();
}
return db;
}
private DB()// 私有无参构造函数
{
sqlConnection = new SqlConnection(@"server=.\SQLEXPRESS;database=test;Trusted_Connection=SSPI;");
sqlConnection.Open();
}
//单例化结束
public DataTable getBySql(string sql, Object[] param)
{//查询
sql = String.Format(sql, param);//用字符串参数替换的形式防止注入
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(new SqlCommand(sql, sqlConnection));
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
public DataTable getBySql(string sql)
{//无参数的查询
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(new SqlCommand(sql, sqlConnection));
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
public void setBySql(string sql, Object[] param)
{ //无查询结果的修改
sql = String.Format(sql, param);//用字符串参数替换的形式防止注入
new SqlCommand(sql, sqlConnection).ExecuteNonQuery();
}
public void setBySql(string sql)
{ //无参数,无查询结果的修改
new SqlCommand(sql, sqlConnection).ExecuteNonQuery();
}
public void Dispose()
{//相当于析构函数
sqlConnection.Close();
//在C#中关闭数据库连接不能在类的析构函数中关,否则会抛“内部 .Net Framework 数据提供程序错误 1”的异常
//通过实现C#中IDisposable接口中的Dispose()方法主要用途是释放非托管资源。
}
}
}
之后,主页面Default.aspx的代码如下,可以看到这次的Repeater没有添加各种ASP.NET独有的事件与属性,完完全全作为一个简单的循环组件来使用的。里面的数据完全是客户端的内容,这里设置修改、添加通过表单的形式来实现,而删除数据则通过Ajax的方式去实现,理论上,全部用Ajax或者表单去完成都可以,反正利用.ashx、Ajax、Session优化Repeater之后,网页编程就变得灵活起来。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RepeaterAjax._Default" %>
<!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>Repeater与Ajax的综合运用</title>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
</head>
<body>
<%--
删去:
<form id="form1" runat="server">
<div>
删去自带的ASP.NET服务端的表单,此表单不影响功能的显示,但会影响到IE的样式
因为理论上,这个服务端表单还是要被编译成普通的表单
而表单中不应该嵌套表单
--%>
<asp:Repeater ID="Repeater1" runat="server">
<%--不循环的部分--%>
<HeaderTemplate>
<table border="1">
<tr>
<th>
用户名
</th>
<th>
密码
</th>
<th colspan="2">
操作
</th>
</tr>
</HeaderTemplate>
<%--根据数据绑定循环部分--%>
<ItemTemplate>
<tr>
<form action='update.ashx' method="post">
<input type="hidden" name="id" value='<%#Eval("id")%>' />
<td>
<input type="text" name="username" value='<%#Eval("username")%>' />
</td>
<td>
<input type="text" name="password" value='<%#Eval("password")%>' />
</td>
<td>
<input type="submit" value="修改" />
</td>
</form>
<td>
<input type="button" οnclick='del(<%#Eval("id")%>)' value="删除" />
</td>
</tr>
</ItemTemplate>
<%--不循环的部分--%>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<b>插入用户:</b><br />
<form action="insert.ashx" method="post">
用户名:<input type="text" name="username" />密码:<input type="text" name="password" /><input
type="submit" value="添加" />
</form>
</body>
<script type="text/javascript">
//删除数据的Ajax处理
function del(id) {
if (confirm("确定删除?")) {
$.ajax({
type: 'post',
url: 'del.ashx',
dataType: "html",
data: {
id: id
},
success: function (data) {
window.history.go(0);
},
error: function (data) {
alert("出错了!请稍候再试!");
}
});
}
}
</script>
</html>
Default.aspx需要注意的是一些影响样式小地方,譬如HTML中表单不得镶嵌表单,也就是<form>中不应该再有<form>节点,无论这个form是服务端的form还是客户端的form。同时还有《【HTML】表单form中一单回车就提交的text、一点击就提交的button》( 点击打开链接)的问题。
Default.aspx的后端编程也变得简单起来了,Default.aspx.cs的代码如下所示,就做两件事:一、将数据库的数据加载到Repeater,让其循环,二、判断各个处理的.ashx是否有提示信息返回,有就加载,提示信息的载体就是Session中的info key。各个操作的处理代码,分别写在不同的.ashx这样好管理。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RepeaterAjax
{
public partial class _Default : System.Web.UI.Page
{
DB db;
protected void Page_Load(object sender, EventArgs e)
{
db = DB.getInstance();
if (!Page.IsPostBack)
{
Repeater1.DataSource = db.getBySql("select * from [user_info]");
Repeater1.DataBind();
}
if (Session["info"] != null)
{
Response.Write(Session["info"]);
Session.Remove("info");//用完就销毁,减轻服务器的负担,相当于jsp的request容器
}
}
}
}
接下来,则是各个.ashx,首先是简单的删除数据的处理del.ashx,进行完简单的数据库处理之后,压一个提示信息到Session的info中,Default.aspx在Ajax处理完,则刷新一下页面即可读到这个Session与更新Repeater数据,刷新页面Default.aspx.cs的Page_Load(object sender, EventArgs e)方法会再运行一次。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;//要在ashx文件中使用session就必须加这个
namespace RepeaterAjax
{
/// <summary>
/// 删除数据库数据
/// </summary>
public class del : IHttpHandler, IRequiresSessionState//要在ashx文件中使用session就必须调用这个接口
{
public void ProcessRequest(HttpContext context)
{
DB db = DB.getInstance();
context.Response.ContentType = "text/plain";
db.setBySql("delete from [user_info] where [id]={0}", new Object[] { context.Request.Form["id"] });
context.Session["info"] = "<b>已删除!</b>";
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
唯一需要注意的是,在.ashx一旦使用到Session必须引入相应的头文件,实现相应的接口,它不想aspx.cs一齐都帮你搞好的,如果你不这样整,就会出现如下图的“未将对象引用设置到对象的实例”的错误:
接下来处理表单的插入数据insert.ashx与处理Ajax的del.ashx大同小异,只是处理完,要重定向会Default.aspx页面,重定向到Default.aspx页面Default.aspx.cs的Page_Load(object sender, EventArgs e)方法也会再运行一次的,完成Repeater的数据再绑定,也就是更新Repeater与读取Session的info操作。
需要注意的是重定向到Default.aspx,要在其方法后面补一个false,具体原因在《【ASP.NET】System.Threading.ThreadAbortException中第一次偶然出现的“mscorlib.dll”类型的异常》(点击打开链接)说过,这里不再赘述。
具体代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;//要在ashx文件中使用session就必须加这个
namespace RepeaterAjax
{
/// <summary>
/// 插入数据的处理
/// </summary>
public class insert : IHttpHandler, IRequiresSessionState//要在ashx文件中使用session就必须调用这个接口
{
public void ProcessRequest(HttpContext context)
{
DB db = DB.getInstance();
context.Response.ContentType = "text/plain";
string username = context.Request.Form["username"];
string password = context.Request.Form["password"];
if (username.Trim().Equals("") || password.Trim().Equals(""))
{
context.Session["info"] = "<b>用户名,密码不得为空!</b>";
}
else
{
if (db.getBySql("select * from [user_info] where [username]='{0}'", new Object[] { username }).Rows.Count == 0)
{
db.setBySql("insert into [user_info]([username],[password]) values('{0}','{1}')", new Object[] { username, password });
context.Session["info"] = "<b>添加成功!</b>";
}
else
{
context.Session["info"] = "<b>已有该用户名!</b>";
}
}
context.Response.Redirect("Default.aspx", false);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
而数据的修改处理update.ashx完全与insert.ashx同理,就数据库的SQL语句不同而已,具体代码如下,不再赘述了:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;//要在ashx文件中使用session就必须加这个
namespace RepeaterAjax
{
/// <summary>
/// 修改数据的处理
/// </summary>
public class update : IHttpHandler, IRequiresSessionState//要在ashx文件中使用session就必须调用这个接口
{
public void ProcessRequest(HttpContext context)
{
DB db = DB.getInstance();
context.Response.ContentType = "text/plain";
string id = context.Request.Form["id"];
string username = context.Request.Form["username"];
string password = context.Request.Form["password"];
if (username.Trim().Equals("") || password.Trim().Equals(""))
{
context.Session["info"] = "<b>用户名,密码不得为空!</b>";
}
else
{
if (db.getBySql("select * from [user_info] where [username]='{0}'", new Object[] { username }).Rows.Count == 0)
{
db.setBySql("update [user_info] set [username]='{0}' where [id]={1}", new Object[] { username, id });
db.setBySql("update [user_info] set [password]='{0}' where [id]={1}", new Object[] { password, id });
context.Session["info"] = "<b>已修改!</b>";
}
else
{
context.Session["info"] = "<b>已有该用户名!</b>";
}
}
context.Response.Redirect("Default.aspx", false);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}