AddUser.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>
<form action="AddUser.ashx" method="post">
<table border="">
<tr>
<td>
ID:
</td>
<td>
<input type="text" name="txtId" value="" />
</td>
</tr>
<tr>
<td>
姓名:
</td>
<td>
<input type="text" name="txtName" value="" />
</td>
</tr>
<tr>
<td>
邮箱:
</td>
<td>
<input type="password" name="txtEmail" value="" />
</td>
</tr>
<tr>
<td>
地址:
</td>
<td>
<input type="text" name="txtAddress" value="" />
</td>
</tr>
<tr>
<td colspan="" align="center">
<input type="submit" name="" value="注册" />
</td>
</tr>
</table>
</form>
</body>
</html>

AddUser.ashx

 <%@ WebHandler Language="C#" Class="AddUser" %>

 using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient; public class AddUser : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write("Hello World"); string str = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
//string sql = string.Format("insert into student(id, name, email, address) values(id, name, email, address)");
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand())
{
//分开写cmd的参数
con.Open();
cmd.CommandText = "insert into student(id, name, email, address) values(@id, @name, @email, @address)";
cmd.Connection = con;
cmd.Parameters.Add("@id", context.Request.Form["txtId"]);
cmd.Parameters.Add("@name", context.Request.Form["txtName"]);
cmd.Parameters.Add("@email", context.Request.Form["txtEmail"]);
cmd.Parameters.Add("@address", context.Request.Form["txtAddress"]);
if (cmd.ExecuteNonQuery() > )
{
//重定向,跳转
context.Response.Redirect("UserList.ashx");
context.Response.Write("注册成功!");
}
else
{
context.Response.Write("注册失败!");
}
}
} } public bool IsReusable
{
get
{
return false;
}
} }
05-11 20:17