1 get
Get方式将数据发送到服务端,那么会将用户在表单中的数据放置到浏览器的地址栏中发送到服务器
格式:表单元素name属性的值=用户输入的值
请求地址:http://localhost:59448/GetAndPost.ashx?txtName=123&txtPwd=123
接收方式: string userName = context.Request.QueryString["txtName"];//接收表单元素name的值
2 Post
Post方式将数据发送到服务端,那么会将用户在表单中的数据放置请求报文体中发送到服务器
格式:表单元素name属性的值=用户输入的值
请求地址:http://localhost:59448/GetAndPost.ashx
接收方式:string userName = context.Request.Form["txtName"];//接收表单元素name的值
3 HTML 页和.ashx的相互合作
//读取模板文件
string filePath = context.Request.MapPath("AddSelf.html");
string fileContent = File.ReadAllText(filePath);
context.Response.Write(fileContent);
4 现在来做一个自增的效果页面

<!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 method="post" action="AddSelf.ashx"> <input type="text" name="txtNum" value="&num"/> <input type="submit" value="计算"/> </form> </body> </html>

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace ASP.NETTest { /// <summary> /// AddSelf 的摘要说明 /// </summary> public class AddSelf : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //读取模板文件 string filePath = context.Request.MapPath("AddSelf.html"); string fileContent = File.ReadAllText(filePath); //获取文本框的值 int num; if (Int32.TryParse(context.Request.Form["txtNum"].ToString(),out num)) { //设置文本框的值加1 num++; } //替换文本框的值 fileContent = fileContent.Replace("&num",num.ToString()); context.Response.Write(fileContent); } public bool IsReusable { get { return false; } } } }
5 改进一下,通过span标签展示

<!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 method="post" action="AddSelf.ashx"> <span>&num</span> <input type="submit" value="计算"/> <input type="hidden" name="hidName" value="1" /> <input type="hidden" name="hidResult" value="&num" /> </form> </body> </html>

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace ASP.NETTest { /// <summary> /// AddSelf 的摘要说明 /// </summary> public class AddSelf : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //读取模板文件 string filePath = context.Request.MapPath("AddSelf.html"); string fileContent = File.ReadAllText(filePath); //获取文本框的值 int num; if (Int32.TryParse(context.Request.Form["hidResult"], out num)) { //设置文本框的值加1 num++; } //替换文本框的值 fileContent = fileContent.Replace("&num",num.ToString()); context.Response.Write(fileContent); } public bool IsReusable { get { return false; } } } }