Asp.net中IsPostBack這個屬性相信大家一定經常用吧 判斷是否為回傳很多人說做項目時, pageload事件裡 都要加上
protectedvoidPage_Load(objectsender, EventArgs e)
{
if(!IsPostBack)
{
}
}
但是確不太理解原因 說加上這個肯定沒錯 可是 上篇的例子裡 不就錯了嗎? 所以 一定要理解原理~~為了把這個說清楚 這裡不用asp.net頁面 用html+handler 一般處理常式來講清這個我先把代碼貼出來html的
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<formaction="Hello2.ashx"method="post">
<inputtype="hidden"name="ispostback"class="night"value="true"/>
姓名:<inputtype="text"id="fasdfasd"name="UserName"value="@value"/><inputtype="submit"value="提交"/>
@msg
</form>
</body>
</html>
handler的
publicvoidProcessRequest (HttpContext context) {
context.Response.ContentType="text/html";
stringusername=context.Request["UserName"];
stringmsg="";
stringispostback=context.Request["ispostback"];//
if(ispostback=="true")//如果提交了這個參數則說明是提交表單進來的
{
context.Response.Write("提交進入");
msg=username+"你好";
}
else
{
context.Response.Write("直接進入");
username="";
msg="";
}
stringfullpath=context.Server.MapPath("Hello2.htm");//得到檔案的全路徑
stringcontent=System.IO.File.ReadAllText(fullpath);//讀取檔案
content=content.Replace("@value",username);
content=content.Replace("@msg", msg);
context.Response.Write(content);
}
publicboolIsReusable {
get{
returnfalse;
}
}
這個貼出來 相信大家一看就明白怎麼回事了 我大概說下上來先運行 handler 因為第一次運行 context.Request["ispostback"]; 肯定是空的 所以直接進入 然後讀取html 把裡面的內容輸出到頁面上 (預留位置@value等 為了實現儲存頁面狀態 類比asp.net)
這時點提交時 包括以後點提交時 因為有下面這句 所以ispostback一直就是true了<inputtype="hidden"name="ispostback"class="night"value="true"/>
這也就造成很多人說 ispostback是 判斷是否是第一次進入 其實 你進入以後 點重新整理 依然會發現 ispostback 不為true 因為並沒有提交實現一次回傳
這個說的有點亂了~~ 但是基本原理就這樣 希望對新手有協助
多看下上面的代碼 複製下來運行試試 就明白啦~ 不懂下面留言 歡迎討論
這裡補充下用途
protectedvoidPage_Load(objectsender, EventArgs e)
{
if(!IsPostBack)
{
// 執行資料繫結 等
}
}
在裡面執行資料繫結 減少不必要的與資料庫互動
如果不加這個判斷 當你點擊按鈕時 每次都是先執行Page_Load 再執行 事件的
這就造成點一次 按鈕 執行下資料繫結 與資料庫互動很費資源
但加上 這個判斷 則沒有這個問題了~~