ASP.Net学习笔记005--ASP.Net的IsPostBack揭秘

来源:互联网 发布:令狐公子 知乎 编辑:程序博客网 时间:2024/05/17 10:04
以前写的课程都没有附上源码,很抱歉!
课程中的源码可以加qq索要:1606841559
技术交流qq1群:251572072
技术交流qq2群:170933152
也可以自己下载:
ASP.Net学习笔记005ASP.Net的IsPostBack揭秘.zip
http://credream.7958.com/down_20144364.html
1.IsPostBack就是上课中说的:
  如果表单没有提交,那么IsPostBack就是false,如果表单提交了IsPostBack就是true
2.上课中,通过判断提交的内容是否是空或者空字符串来判断的,这样是有些不合理的,如果后台
  需要接收一个空,或者空字符串的时候,这个时候,用这个判断是有问题的
3.可以加一个字段解决:
http://localhost:61248/WebSite1/Hello2.ashx?IsPostBack=true&UserName=UserName
4.并且,如果想反回提交的值,可以通过替换自定义字段的形式,实现
接着上课工程:
/WebSite1
Hello2.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
<form action="Hello2.ashx">
<input type="hidden" name="IsPostBack" value="true" />
姓名:<input type="text"  value="@value" name="UserName"/>
     <input type="submit" value="提交" />
     @msg
     <!--
     服务器只认name属性,而且name属性如果重复,会只提交第一个
     id是给dom用的
     -->
</form>
</body>
</html>
---------------------------------------------------------------------------
Hello2.ashx
<%@ WebHandler Language="C#" Class="Hello2" %>


using System;
using System.Web;


public class Hello2 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
    
       //---------上课内容---------- 
       // string username=context .Request ["UserName"];
 //    if (string.IsNullOrEmpty (username )){
 //        context.Response.Write("直接进入");
 //    }
 //else
 //{
 //    context.Response.Write("提交进入");
 //    }
        // context.Response.Write("Hello World");


        //---------上课内容---------- 


        string msg = "";
        string usernmae=context .Request["UserName"];
        
        //**********************************************
        string isPostBack =context.Request["IsPostBack"];
        if (isPostBack =="true"){
            context.Response.Write("提交进入");
            msg =usernmae+"--hello credream";
        }else{
            context.Response.Write("直接进入");
            usernmae = "";
            msg = "";
        }
        //当直接访问的时候http://localhost:61248/WebSite1/Hello2.ashx,因为后面没有参数,所以这个时候,
        //显示直接进入,当,填写入内容的时候,因为后面有参数了,所以是提交进入
        //http://localhost:61248/WebSite1/Hello2.ashx?IsPostBack=true&UserName=UserName
        string fullPath = context.Server.MapPath("Hello2.htm");//取得文件全路径
        string content = System.IO.File.ReadAllText(fullPath);//取得文件全内容
        content.Replace("@value",usernmae);
        content.Replace("@msg", msg);
        //直接访问这个文件也会被调用
        context.Response.Write(content);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }


}


--------------------------------------------------------------------------------
0 0