一般处理程序完成增删改查

来源:互联网 发布:生活 知乎 编辑:程序博客网 时间:2024/04/30 02:12

以前在学校ASP.NET都是用控件(如gridview),今天第一次接触用一般处理程序(.ashx)实现单表增删改查。

百度云盘下载链接:http://pan.baidu.com/share/link?shareid=388570&uk=3627406265

前期准备:数据表如下:

image

SqlHelper文件,

View Code
 1 private static readonly string conStr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; 2         public static int ExecuteNonQuery(string sqlText, params SqlParameter[] paras) 3         { 4             using (SqlConnection conn=new SqlConnection(conStr) ) 5             { 6                 using (SqlCommand cmd=new SqlCommand(sqlText,conn)) 7                 { 8                     if (paras!=null) 9                     {10                         cmd.Parameters.AddRange(paras);11                     }12                     conn.Open();13                     return cmd.ExecuteNonQuery();14                 }15             }16         }17         public static object ExecuteScalar(string sqlText, params SqlParameter[] paras)18         {19             using (SqlConnection conn=new SqlConnection(conStr))20             {21                 using (SqlCommand cmd=new SqlCommand(sqlText,conn))22                 {23                     if (paras!=null)24                     {25                         cmd.Parameters.AddRange(paras);26                     }27                     conn.Open();28                     return cmd.ExecuteScalar();29                 }30             }31         }32         public static SqlDataReader ExecuteReader(string sqlText, params SqlParameter[] paras)33         {34             SqlConnection conn=new SqlConnection(conStr);35             using (SqlCommand cmd=new SqlCommand(sqlText,conn))36             {37                 if (paras!=null)38                 {39                     cmd.Parameters.AddRange(paras);40                         41                 }42                43                 try44                 {45                     conn.Open();46                     return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);47 48                 }49                 catch (Exception)50                 {51                     conn.Close();52                     conn.Dispose();53                     throw;54                 }55             }             56         }57         public static DataTable ExecuteDataTable(string sqlText, params SqlParameter[] paras)58         {59             using (SqlDataAdapter da=new SqlDataAdapter(sqlText,conStr))60             {61                 if (paras!=null)62                 {63                     da.SelectCommand.Parameters.AddRange(paras);64                 }65                 DataTable dt = new DataTable();66                 da.Fill(dt);67                 return dt;68             }69         }

 

web.config添加connectionStrings节点

View Code
1 <connectionStrings>2     <add name="sql" connectionString="data source=.\sqlexpress;database=DBTest;uid=sa;pwd=123456"/>3   </connectionStrings>

 

一、登录:

1、新建登陆页面Login.htm:

View Code
1 <form method="post" action="ProcessLogin.ashx">2         <table>3             <tr><td>用户名:</td><td><input type="text" name='userName'/></td></tr>4             <tr><td>密码</td><td><input type="text" name="pwd" /></td></tr>5             <tr><td colspan="2"><input type="submit" value="登录" /></td></tr>6         </table>7  </form>

 

2、新建一般处理程序ProcessLogin.ashx

要点:右键添加一般处理程序即可

context.Response.ContentType = "text/html";是告诉浏览器,报文体内容解析为htmlstring html = System.IO.File.ReadAllText(context.Request.MapPath("Login.htm"));读取Login.htm内容,存到字符串中

View Code
 1 //告诉浏览器,报文体内容解析为html 2         context.Response.ContentType = "text/html"; 3         var name=context.Request.Form["userName"]; 4         var pwd=context.Request.Form["pwd"]; 5         string sqlText="select count(*) from T_Student where  name=@name and password=@password"; 6         SqlParameter[] paras=new SqlParameter[]{ 7             new SqlParameter("@name",name), 8             new SqlParameter("@password",pwd) 9         };10         //查询用户名密码是否正确11         int i = (int)Helper.SQLHelper.ExecuteScalar(sqlText, paras);12         if (i>0)13         {14             context.Response.Redirect("UserList.ashx");15         }16         else17         {18             //如果错误,则重新输入Login.htm页面,并保存用户名19             string html = System.IO.File.ReadAllText(context.Request.MapPath("Login.htm"));20             html = html.Replace("name='userName'", "name='userName' value='"+name+"'");21             context.Response.Write(html);22         }

 

二、用户信息列表

1、新建UserList.htm

要点:该页面作为用户信息列表的模版,写好表格表头后,加@DataRow,便于在一般处理程序用替换@DataRow。

View Code
 1 <form action="ProcessLogin.ashx" method="post"> 2     <table> 3         <thead> 4             <tr> 5                 <th> 6                     编号 7                 </th> 8                 <th> 9                     用户名10                 </th>11                 <th>12                     密码13                 </th>14                 <th>15                     操作16                 </th>17             </tr>18         </thead>19         @DataRow20     </table>21     </form>

 

2、新建UserList.ashx

要点,获取模版UserList.htm字符串,将数据库用户信息读取出来,遍历追加到StringBuilder,并将@DataRow替换。在详情、删除、修改超链接中分别填写好跳转地址

View Code
 1 context.Response.ContentType = "text/html"; 2         string sqlText = "select * from T_Student"; 3         DataTable dt = Helper.SQLHelper.ExecuteDataTable(sqlText); 4         //读取模版UserList.htm内容 5         string temp = File.ReadAllText(context.Server.MapPath("UserList.htm")); 6         StringBuilder sb = new StringBuilder(); 7         foreach (DataRow item in dt.Rows) 8         { 9             //追加用户信息和操作10             sb.AppendFormat(@"<tr><td>{0}</td><td>{1}</td><td>{2}</td>11                                 <td>12                                     <a href='ShowUserInfo.ashx?id={0}'>详情</a>13                                     <a href='DeleteUser.ashx?id={0}'>删除</a>14                                     <a href='EditUser.ashx?id={0}'>修改</a>15                                 </td>16                               </tr>", item["id"],item["name"],item["password"]); 17         }18         //将@DataRow替换为StringBuilder内容19         temp=temp.Replace("@DataRow",sb.ToString());20         context.Response.Write(temp);

 

3、登录成功后,用post方式,将报文提交到UserList.ashx,返回相应报文。效果如下。

image

三、查看用户详情。

1、添加ShowUserInfo.htm模版

要点:因为编号不需显示,但需要用编号查询用户信息。所以把id放到隐藏域中。<input type="hidden" name="id" />

View Code
1 <input type="hidden" name="id" />2     <table>3         <tr><td>用户名:</td><td>@userName</td></tr>4         <tr><td>密码:</td><td>@password</td></tr>5     </table>

 

2、ShowUserInfo.ashx

View Code
 1 context.Response.ContentType = "text/html"; 2         //获取Get传递过来的id 3         int id = context.Request.QueryString["id"] == null ? 0 : int.Parse(context.Request.QueryString["id"]); 4         if (id>0) 5         { 6             string sqlText = "select name,password from dbo.T_Student where id=@id"; 7             //从数据库根据id获取用户信息 8             DataTable dt = Helper.SQLHelper.ExecuteDataTable(sqlText,new SqlParameter("@id",id)); 9             //获取ShowUserInfo.htm页面内容10             string temp = File.ReadAllText(context.Server.MapPath("ShowUserInfo.htm"));11             //替换ShowUserInfo.htm页面内容12             temp = temp.Replace("@userName",dt.Rows[0]["name"].ToString());13             temp = temp.Replace("@password", dt.Rows[0]["password"].ToString());14             context.Response.Write(temp);15         }

 

3、在UserList.ashx点击详情,效果如下

image

四、删除用户。

1、点击删除前,提示用户(在UserList.html中用Jquery实现)

View Code
 1 <script src="js/jquery-1.4.1.js" type="text/javascript"></script> 2     <script type="text/javascript"> 3         $(function () { 4             $("a:contains('删除')").click(function () { 5             //如果点击取消,则取消跳转(不执行DeleteUser.ashx文件) 6                 if (!confirm("确定要删除么?")) { 7                     return false; 8                 } 9             });10         });11     </script>

 

2、DeleteUser.ashx

View Code
 1 context.Response.ContentType = "text/html"; 2         //获取Get传递过来的id 3         int id = context.Request.QueryString["id"] == null ? 0 : int.Parse(context.Request.QueryString["id"]); 4         if (id>0) 5         { 6             string sqltext = "delete from T_Student where id=@id"; 7             //根据id删除用户 8             int i=Helper.SQLHelper.ExecuteNonQuery(sqltext, new SqlParameter("@id",id)); 9             if (i>0)10             {11                 //删除成功则跳转到用户信息列表页12                 context.Response.Redirect("UserList.ashx");13             }14             else15             {16                 context.Response.Write("删除失败");17             }18         }

 

五、修改用户信息:

1、EditUser.htm

View Code
1 <form method="post" action="ProcessEdit.ashx">2         <table>3             <input type="hidden" name="id" value="@id"/>4             <tr><td>用户名:</td><td><input type="text" name='userName' value="@name"/></td></tr>5             <tr><td>密码</td><td><input type="text" name="password" value="@pwd" /></td></tr>6             <tr><td colspan="2"><input type="submit" value="修改" /></td></tr>7         </table>8     </form>

 

2、EditUser.ashx显示要修改的用户信息。

View Code
 1 context.Response.ContentType = "text/html"; 2         int id = context.Request.QueryString["id"] == null ? 0 : int.Parse(context.Request.QueryString["id"]); 3         if (id>0) 4         { 5             string sqlText = "select name,password from T_Student where id=@id"; 6             DataTable dt = Helper.SQLHelper.ExecuteDataTable(sqlText, new SqlParameter("@id", id)); 7             string temp=File.ReadAllText(context.Server.MapPath("EditUser.htm")); 8             temp=temp.Replace("@id",id.ToString()); 9             temp=temp.Replace("@name",dt.Rows[0]["name"].ToString());10             temp=temp.Replace("@pwd",dt.Rows[0]["password"].ToString());11             context.Response.Write(temp);12         }

 

3、ProcessEdit.ashx处理修改

View Code
 1 context.Response.ContentType = "text/html"; 2         int id = context.Request.Form["id"] == null ? 0 : int.Parse(context.Request.Form["id"]); 3         if (id>0) 4         { 5             string name = context.Request.Form["userName"]; 6             string password = context.Request.Form["password"]; 7             string sqltext = "update T_Student set name=@name,password=@password where id=@id"; 8             SqlParameter[] paras = new SqlParameter[]{ 9                 new SqlParameter("@id",id),10                 new SqlParameter("@name",name),11                 new SqlParameter("@password",password)12             };13             int i = Helper.SQLHelper.ExecuteNonQuery(sqltext,paras);14             if (i>0)15             {16                 context.Response.Redirect("UserList.ashx");17             }18             else19             {20                 context.Response.Write("修改失败");21             }22         }

 


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>