post详解,IsPostBack原理详解

这个属性相信大家一定经常用吧 判断是否为回发 (切记这是判断是否回发 而听到很多人说这是判断是否第一次加载页面 还有的说是否为刷新 )
很多人说做项目时 pageload事件里 都要加上
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } }

但是确不太理解原因 说加上这个肯定没错 可是 上篇的例子里 不就错了么? 所以 一定要理解原理~~
为了把这个说清楚 这里不用asp.net页面 用html+handler 一般处理程序来讲清这个
我先把代码贴出来
html的
姓名: @msg

handler的
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/html"; string username = context.Request["UserName"]; string msg = ""; string ispostback = context.Request["ispostback"];// if (ispostback=="true")//如果提交了这个参数则说明是提交表单进来的 { context.Response.Write("提交进入"); msg = username + "你好"; } else { context.Response.Write("直接进入"); username = ""; msg = ""; } string fullpath = context.Server.MapPath("Hello2.htm");//得到文件的全路径 string content = System.IO.File.ReadAllText(fullpath);//读取文件 content = content.Replace("@value",username); content = content.Replace("@msg", msg); context.Response.Write(content); } public bool IsReusable { get { return false; } }

这个贴出来 相信大家一看就明白怎么回事了 我大概说下
上来先运行 handler 因为第一次运行
context.Request["ispostback"]; 肯定是空的 所以直接进入 然后读取html 把里面的内容输出到页面上 (占位符@value等 为了实现保存页面状态 模拟asp.net) 这时点提交时 包括以后点提交时 因为有下面这句 所以 ispostback一直就是true了
这也就造成很多人说 ispostback是 判断是否是第一次进入 其实 你进入以后 点刷新 依然会发现 ispostback 不为true 因为并没有提交实现一次回发 这个说的有点乱了~~ 但是基本原理就这样 希望对新手有帮助 多看下上面的代码 复制下来运行试试 就明白啦~ 不懂下面留言 欢迎讨论
Tags:  postback 红外白板原理详解 post详解

延伸阅读

最新评论

发表评论