直接上代码:

HTML代码,其中表单中input标签中的value值首先用一个占位符占位,然后在ashx中将其替换

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
<form action = "02jsqHandler.ashx" method = "post">
    <input type = "text" name = "txtNum1" value = "@txtNum1" />+
    <input type = "text" name = "txtNum2" value = "@txtNum2" />
    =<input type = "text" name = "txtResult" value = "@txtResult" />
    <input type = "hidden" name = "IsPostBack" value = "false" />
    <input type = "submit"  value = "计算" />
</form>
</body>
</html>

ashx代码:

首先用io中的File.ReadAllText()方法将html文件读出来

public class _02jsqHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
        //获得html文件的内容
        string path = context.Server.MapPath("03jsq2.htm");
        string strHtml = File.ReadAllText(path);
        //声明三个整形变量
        int n1 = 0, n2 = 0, result = 0;
        bool ispostback = Convert.ToBoolean(context.Request.Form["IsPostBack"]);
        if (!ispostback)  //判断是否是第一次加载相当于aspx.cs中的IsPostBack
        {
            //分别获得数1和数2
            string sn1 = context.Request.Form["txtNum1"];
            string sn2 = context.Request.Form["txtNum2"];
            if (int.TryParse(sn1, out n1) && int.TryParse(sn2, out n2))
            {
                result = n1 + n2;
            }
            //context.Response.Write(result.ToString());
        }
        //将html中的@参数(占位符替换为对应的数据)
        strHtml = strHtml.Replace("@txtNum1", n1.ToString())
            .Replace("@txtNum2", n2.ToString())
            .Replace("@txtResult", result.ToString());
        //将html写回页面
        context.Response.Write(strHtml);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

 

 posted on 2012-04-20 22:01  WlitSoft  阅读(594)  评论(2编辑  收藏  举报