IsPostBack原理详解

这个属性相信大家一定经常用吧  判断是否为回发 (切记这是判断是否回发  而听到很多人说这是判断是否第一次加载页面  还有的说是否为刷新 )

很多人说做项目时  pageload事件里 都要加上

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

}
}

但是确不太理解原因   说加上这个肯定没错 可是 上篇的例子里 不就错了么? 所以 一定要理解原理~~

为了把这个说清楚 这里不用asp.net页面 用html+handler 一般处理程序来讲清这个

我先把代码贴出来

html的

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form action="Hello2.ashx" method="post">
<input type="hidden" name="ispostback" class="night" value="true" />
姓名:
<input type="text" id="fasdfasd" name="UserName" value="@value" /><input type="submit" value="提交" />
@msg
</form>
</body>
</html>
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了
<input type="hidden" name="ispostback" class="night"  value="true" />
这也就造成很多人说 ispostback是 判断是否是第一次进入 其实 你进入以后 点刷新 依然会发现 ispostback 不为true 因为并没有提交实现一次回发

这个说的有点乱了~~ 但是基本原理就这样 希望对新手有帮助

多看下上面的代码 复制下来运行试试 就明白啦~ 不懂下面留言 欢迎讨论


这里补充下用途
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 执行数据绑定 等
}
}
在里面执行数据绑定 减少不必要的与数据库交互

如果不加这个判断 当你点击按钮时 每次都是先执行Page_Load 再执行 事件的

这就造成点一次 按钮 执行下数据绑定 与数据库交互很费资源

但加上 这个判断 则没有这个问题了~~

posted on 2011-06-28 11:26  wlf  阅读(2039)  评论(12编辑  收藏  举报