员工Emp表的增删改查实现!本实验室目的是为了了解模板页的好处!
1、使用字符串拼接的不好的地方:
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace Web1.Day3 { /// <summary> /// EmpView 的摘要说明 /// </summary> public class EmpView : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //给定一个id=?就可以显示出来这个人的信息 int id = Convert.ToInt32(context.Request["id"]);//id输入是否合法,还可以判断 DataTable table= SqlHelper.ExecuteQuery("select * from Emp where id=@id",new SqlParameter("@id",id) ); if (table.Rows.Count<0) { OutputHtmlStart("错误");//如果出错显示 context.Response.Write("不存在的id"); OutputHtmlEnd(); return; } /*row又不是值类型,因此不会复制数据副本,所以它指向的是table表的第一行,但是row会自己开辟一个存储空间 * 存放mytable第一行的内存地址,而不是行的数据内容. */ DataRow row=table.Rows[0]; string name=(string)row["Name"]; int age=(int)row["Age"]; OutputHtmlStart("查看" + name);//正常显示 context.Response.Write("<table><tr><td>姓名</td><td>"+name+"</td><tr>"); context.Response.Write("<tr><td>年龄</td><td>"+age+"</td><tr>"); OutputHtmlEnd(); } private void OutputHtmlStart(string title) { HttpContext.Current.Response.Write("<html><head><title>"+title+"</title></head><body>"); } private void OutputHtmlEnd() { HttpContext.Current.Response.Write("</body></html>"); } public bool IsReusable { get { return false; } } } }
2、改用模板页的写法后,实现美工和C#程序分工的合作;
首先建立一个模板页:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>@name</title> </head> <body> <table> <tr><td style="color:red">姓名</td><td onclick="alert('@name你好');">@name</td></tr> <tr><td>年龄</td><td>@age</td></tr> </table> </body> </html>
3、再用字符串进行代替
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Web; namespace Web1.Day3 { /// <summary> /// EmpView2 的摘要说明 /// </summary> public class EmpView2 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //给定一个id=?就可以显示出来这个人的信息 int id = Convert.ToInt32(context.Request["id"]);//id输入是否合法,还可以判断 DataTable table = SqlHelper.ExecuteQuery("select * from Emp where id=@id", new SqlParameter("@id", id)); if (table.Rows.Count <= 0) { return; } DataRow row = table.Rows[0]; string name = (string)row["Name"]; int age = (int)row["Age"]; string EmpviewHtmlfileName = context.Server.MapPath("~/Day3/EmpView2.html"); string EmpviewHtmlfile = File.ReadAllText(EmpviewHtmlfileName); EmpviewHtmlfile = EmpviewHtmlfile.Replace("@name", name).Replace("@age", age.ToString());//替换自己定义的@name // EmpviewHtmlfile = personViewHtml.Replace("@name", name); //EmpviewHtmlfile = personViewHtml.Replace("@age", age.ToString()); context.Response.Write(EmpviewHtmlfile); } public bool IsReusable { get { return false; } } } }
细节;id 还是 i -----------------------;;半个笑死
4、下面对重复的代码块,进行抽象成一个类,并封装为一个方法,会发现代码越写越简单
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace Web1.Day3 { public class CommonHelper { /// <summary> /// 读取虚拟路径下的html文件,并返回文件内容 /// </summary> /// <param name="virtualPath"></param> /// <returns></returns> public static string ReadHtml(string virtualPath) { string fullPath = HttpContext.Current.Server.MapPath(virtualPath); string htmlCharcters = File.ReadAllText(fullPath); return htmlCharcters; } /// <summary> /// 输出报错消息 /// </summary> /// <param name="msg"></param> public static void OutputError(string msg) { string html = ReadHtml("~/Day3/Error.html");//只是读取错误页面的模板页 html=html.Replace("{msg}",msg); HttpContext.Current.Response.Write(html); } } } 5、采用错误模板页,展示模板页 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>@name</title> </head> <body> <table> <tr><td style="color:red">姓名</td><td onclick="alert('@name你好');">@name</td></tr> <tr><td>年龄</td><td>@age</td></tr> </table> </body> </html> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>错误</title> </head> <body> <table> <tr><td onclick="alert('{msg}');">{msg}</td></tr> </table> </body> </html>
6、对逻辑页面进行简化处理;
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Web; namespace Web1.Day3 { /// <summary> /// EmpView2 的摘要说明 /// </summary> public class EmpView2 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //给定一个id=?就可以显示出来这个人的信息 string strId=context.Request["id"]; if (string.IsNullOrEmpty(strId)) { CommonHelper.OutputError("请输入您要查询的id!"); return; } int id = Convert.ToInt32(context.Request["id"]);//id输入是否合法,还可以判断 DataTable table = SqlHelper.ExecuteQuery("select * from Emp where id=@id",new SqlParameter("@id", id)); if (table.Rows.Count <= 0) { CommonHelper.OutputError("该id不存在记录!"); return; } DataRow row = table.Rows[0]; string name = (string)row["Name"]; int age = (int)row["Age"]; //string EmpviewHtmlfileName = context.Server.MapPath("~/Day3/EmpView2.html"); //string EmpviewHtmlfile = File.ReadAllText(EmpviewHtmlfileName); string EmpviewHtmlfile = CommonHelper.ReadHtml("~/Day3/EmpView2.html"); EmpviewHtmlfile = EmpviewHtmlfile.Replace("@name", name).Replace("@age", age.ToString());//替换自己定义的@name // EmpviewHtmlfile = personViewHtml.Replace("@name", name); //EmpviewHtmlfile = personViewHtml.Replace("@age", age.ToString()); context.Response.Write(EmpviewHtmlfile); } public bool IsReusable { get { return false; } } } }
7、新建页面人员列表展示页面
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <table> {EmpList} </table> </body> </html>
8、再建一个EmpList.ashx一般处理程序
9、用StringBuilder进行Table表的拼接
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; namespace Web1.Day3 { /// <summary> /// EmpList 的摘要说明 /// </summary> public class EmpList : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html";//1、第一步,因为要输出html //2、查出来整张二维表 DataTable dt = SqlHelper.ExecuteQuery("select * from Emp"); //3、采用StringBuilder来拼接一张二维表显示在EmpList.html中 StringBuilder sb = new StringBuilder(); //4、遍历dt中的每一行,进行拼接Table foreach (DataRow row in dt.Rows) { sb.Append("<tr>"); sb.Append("<td>").Append(row["Name"]).Append("</td>").Append("<td>").Append(row["Age"]).Append("</td>"); sb.Append("</tr>"); } //5、读取列表展示模板页 string EmpListhtml = CommonHelper.ReadHtml("~/Day3/EmpList.html"); //6、替换列表 EmpListhtml = EmpListhtml.Replace("{EmpList}",sb.ToString()); //7、将人员列表展示页输出到浏览器中 context.Response.Write(EmpListhtml); } public bool IsReusable { get { return false; } } } }
10、下面再接着再添加一个删除列,重新修改EmpList.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <table> <thead><tr><th>姓名</th><th>年龄</th><th>删除</th></tr></thead> <tbody> {EmpList} </tbody> </table> </body> </html>
11、js代码在C#中写的时候。最好用单引号;
12、在c#中用js的时候,单引号中写双引号,双引号用反斜线转义。
13、添加删除列的一般处理程序
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; namespace Web1.Day3 { /// <summary> /// EmpList 的摘要说明 /// </summary> public class EmpList : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html";//1、第一步,因为要输出html //2、查出来整张二维表 DataTable dt = SqlHelper.ExecuteQuery("select * from Emp"); //3、采用StringBuilder来拼接一张二维表显示在EmpList.html中 StringBuilder sb = new StringBuilder(); //4、遍历dt中的每一行,进行拼接Table foreach (DataRow row in dt.Rows) { sb.Append("<tr>"); sb.Append("<td>").Append(row["Name"]).Append("</td>").Append("<td>").Append(row["Age"]).Append("</td>") .Append("<td><a onclick='return confirm(\"确定要删除吗?\")' href='EmpListDelete.ashx?id=").Append(row["id"]).Append("'>删除</a></td>"); sb.Append("</tr>"); } //5、读取列表展示模板页 string EmpListhtml = CommonHelper.ReadHtml("~/Day3/EmpList.html"); //6、替换列表 EmpListhtml = EmpListhtml.Replace("{EmpList}",sb.ToString()); //7、将人员列表展示页输出到浏览器中 context.Response.Write(EmpListhtml); } public bool IsReusable { get { return false; } } } }
14、添加删除页面一般处理程序
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; namespace Web1.Day3 { /// <summary> /// EmpListDelete 的摘要说明 /// </summary> public class EmpListDelete : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html";//第一步 //2、拿到删除人的id int id = Convert.ToInt32(context.Request["id"]); //3、执行Sql SqlHelper.ExecuteNonQuery("delete from Emp where id=@id", new SqlParameter("@id", id)); context.Response.Redirect("EmpList.ashx");//删除完毕重定向到人员列表页面,起到刷新的作用; } public bool IsReusable { get { return false; } } } }
15、添加“增加人员”功能。。。增加页面和编辑页面使用同一个模板页,只是根据action=Add和action=Eidt来判断是那个。
16、增加页面和编辑页面使用同一个模板页如下:
(这里我使用了<table></table>导致,gender选项无法选中不知为何?。。。。。。。。。。。。。。。。。。。。。。)
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>{actionName}人员</title> </head> <body> 姓名:<input type="text" name="name" value="{name}" /> 性别:<input type="text" name="age" value="{age}" /> 性别选中为男<input type="checkbox" name="gender" {gender} /> <tr><input type="submit" value="保存" /></tr> </body> </html>
17、增加页和编辑处理程序;
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace Web1.Day3 { /// <summary> /// EmpAddnewEdit 的摘要说明 /// </summary> public class EmpAddnewEdit : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string action = context.Request["action"]; string html = CommonHelper.ReadHtml("~/Day3/EmpAddnewEdit.html"); if (action == "addnew") { html = html.Replace("{actionName}", "新增").Replace("{name}", "").Replace("{age}", "18")//默认18岁 .Replace("{gender}", "checked").Replace("{action}", "xinzeng"); context.Response.Write(html); } else if (action == "edit") { int id = Convert.ToInt32(context.Request["id"]); //查询该id的信息 DataTable table = SqlHelper.ExecuteQuery("Select * from Emp123 where Id=@Id", new SqlParameter("@Id", id)); //是否有该人id的记录 if (table.Rows.Count <= 0) { CommonHelper.OutputError("没找到id=" + id + "的人员"); return; } //或者该id有多条记录的出现呢 if (table.Rows.Count > 1) { CommonHelper.OutputError("找到多条id=" + id + "的人员"); return; } //找到该id进行替换模板页 DataRow row = table.Rows[0]; //从table中读取Name,Age ,gender,,方便替换 string name = (string)row["Name"]; int age = (int)row["age"]; bool gender = (bool)row["Gender"]; //这里对男 女需要进行判断,,,checked有,就是男的,没有这个字段就是为不够选 // html = html.Replace("{actionName}", "编辑").Replace("{name}", name).Replace("{age}", age.ToString()) .Replace("{gender}", gender ? "checked" : ""); //重新输出该html到浏览器端 context.Response.Write(html); } else { CommonHelper.OutputError("action错误"); } } public bool IsReusable { get { return false; } } } }
18、对保存:保存出现的问题,服务器不能知道上次,与浏览器发生了。什么。根据Http连接特性知道, 一次连接完毕,就断开了。那么怎么让浏览器知道,当点击的是增加选项的时候,让服务器知道是增加;当点击的是编辑选项的时候,让服务器知道是编辑、这里采用隐藏域这么一个东西。
19、对于保存的处理,使用另一个一般处理程序,采用Form表单的。Post处理方式(保密,美观(地址栏))。
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>{actionName}人员</title> </head> <body> <form action="EmpSave.ashx" method="post"> <input type="hidden" name="action" value="{action}" /> <input type="hidden" name="id" value="{id}" /> 姓名:<input type="text" name="name" value="{name}" /> <br /><br /> 性别:<input type="text" name="age" value="{age}" /> <br /><br /> 性别选中为男<input type="checkbox" name="gender" {gender} /> <br /><br /> <input type="submit" value="保存" /> </form> </body> </html>
20、保存处理程序页面。先对EmpAddnewEdit.ashx进行处理;
html = html.Replace("{actionName}", "新增").Replace("{name}", "").Replace("{age}", "18")//默认18岁 .Replace("{gender}", "checked").Replace("{action}", "xinzeng"); html = html.Replace("{actionName}", "编辑").Replace("{name}", name).Replace("{age}", age.ToString()).Replace("{gender}", gender ? "checked" : "").Replace("{action}", "xiugai").Replace("{id}",id.ToString());//就是编辑的id
再对保存处理程序进行处理EmpSave.ashx
21、对从模板页中读取的数据进行检查;
context.Response.ContentType = "text/html"; //1、读取action 属性 string action = context.Request["action"]; //2 string strName=context.Request["name"]; string strAge=context.Request["age"]; string strGender=context.Request["gender"]; //做检查判断 if (string.IsNullOrEmpty(strName)) { CommonHelper.OutputError("姓名必填!"); return; } if (string.IsNullOrEmpty(strAge)) { CommonHelper.OutputError("年龄必填!"); return; } //做年龄合法判断 int age; if (!int.TryParse(strAge,out age)) { CommonHelper.OutputError("年龄非法!"); return; }
22、当action分别是addnew和edit 和都不是(预防性编程)处理如下;这里注意性别列的处理;;;
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; namespace Web1.Day3 { /// <summary> /// EmpSave 的摘要说明 /// </summary> public class EmpSave : IHttpHandler { //只有浏览器提交的,服务器才能知道。 //是action=addnew还是action=edit是需要浏览器提交过来的 //添加隐藏域 public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //1、读取action 属性 string action = context.Request["action"]; //2 string strName = context.Request["name"]; string strAge = context.Request["age"]; string strGender = context.Request["gender"]; //做检查判断 if (string.IsNullOrEmpty(strName)) { CommonHelper.OutputError("姓名必填!"); return; } if (string.IsNullOrEmpty(strAge)) { CommonHelper.OutputError("年龄必填!"); return; } //做年龄合法判断 int age; if (!int.TryParse(strAge, out age)) { CommonHelper.OutputError("年龄非法!"); return; } if (action == "xiugai") { //拿到编辑的id int id = Convert.ToInt32(context.Request["id"]); //根据id进行修改 SqlHelper.ExecuteNonQuery("Update Emp123 set Name=@Name,Age=@Age,Gender=@Gender where Id=@Id", new SqlParameter("@Name", strName), new SqlParameter("@Age", age),//参数化传递参数 //性别不可能为空。。。。。。。。。。。。。。。。。。 new SqlParameter("@Gender", strGender != null), new SqlParameter("@Id", id)); //更新完毕,重定向 context.Response.Redirect("EmpList.ashx"); } else if (action == "xinzeng") { //执行插入 SqlHelper.ExecuteNonQuery("Insert into Emp123(Name,Age,Gender) values(@Name,@Age,@Gender)", new SqlParameter("@Name", strName), new SqlParameter("@Age", age), new SqlParameter("@Gender", strGender != null));//"on" context.Response.Redirect("EmpList.ashx"); } else { CommonHelper.OutputError("action错误!"); } } public bool IsReusable { get { return false; } } } }