AddUser.html
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 </head> 7 <body> 8 <form action="AddUser.ashx" method="post"> 9 <table border="1"> 10 <tr> 11 <td> 12 ID: 13 </td> 14 <td> 15 <input type="text" name="txtId" value="" /> 16 </td> 17 </tr> 18 <tr> 19 <td> 20 姓名: 21 </td> 22 <td> 23 <input type="text" name="txtName" value="" /> 24 </td> 25 </tr> 26 <tr> 27 <td> 28 邮箱: 29 </td> 30 <td> 31 <input type="password" name="txtEmail" value="" /> 32 </td> 33 </tr> 34 <tr> 35 <td> 36 地址: 37 </td> 38 <td> 39 <input type="text" name="txtAddress" value="" /> 40 </td> 41 </tr> 42 <tr> 43 <td colspan="3" align="center"> 44 <input type="submit" name="" value="注册" /> 45 </td> 46 </tr> 47 </table> 48 </form> 49 </body> 50 </html>
AddUser.ashx
1 <%@ WebHandler Language="C#" Class="AddUser" %> 2 3 using System; 4 using System.Web; 5 using System.Configuration; 6 using System.Data.SqlClient; 7 8 public class AddUser : IHttpHandler 9 { 10 11 public void ProcessRequest(HttpContext context) 12 { 13 context.Response.ContentType = "text/html"; 14 context.Response.Write("Hello World"); 15 16 string str = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; 17 //string sql = string.Format("insert into student(id, name, email, address) values(id, name, email, address)"); 18 using (SqlConnection con = new SqlConnection(str)) 19 { 20 using (SqlCommand cmd = new SqlCommand()) 21 { 22 //分开写cmd的参数 23 con.Open(); 24 cmd.CommandText = "insert into student(id, name, email, address) values(@id, @name, @email, @address)"; 25 cmd.Connection = con; 26 cmd.Parameters.Add("@id", context.Request.Form["txtId"]); 27 cmd.Parameters.Add("@name", context.Request.Form["txtName"]); 28 cmd.Parameters.Add("@email", context.Request.Form["txtEmail"]); 29 cmd.Parameters.Add("@address", context.Request.Form["txtAddress"]); 30 if (cmd.ExecuteNonQuery() > 0) 31 { 32 //重定向,跳转 33 context.Response.Redirect("UserList.ashx"); 34 context.Response.Write("注册成功!"); 35 } 36 else 37 { 38 context.Response.Write("注册失败!"); 39 } 40 } 41 } 42 43 } 44 45 public bool IsReusable 46 { 47 get 48 { 49 return false; 50 } 51 } 52 53 }