在ASP.NET中,頁面回傳(postback)是很常見的一種形式,它用於客戶端和服務端進行交互,從而執行新的頁面生命週期,加載ViewState等,對於客戶端的效果來說,就是你會看到頁面被刷新了,但是這不同於Javascript的刷新。 對於ASP.NET開發者來說,防止頁面刷新最常見的是使用HTML控件並使用JavaScript代碼達到你的目的,或者使用Ajax來執行服務端代碼。而這裏介紹如何阻止Asp.net 服務端控件Button執行postbacks事件,對於複雜一點的GridView控件,我們可以用Update panel或者集成ICallbackEventHandler接口來防止頁面刷新,這些內容將會在以後介紹到:
這裏我們介紹怎麼防止服務器端Button的Postbacks事件,你甚至可以使用CheckBox來選擇是否需要Postback:
原理: 使用OnClientClick事件判斷CheckBox狀態,返回bool值。注意OnClientClick事件定義爲“ return onClientClickEvent()”
[本示例完整源碼下載(0分)] http://download.csdn.net/source/3450349
StopPostBack.aspx 代碼
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
//Use ClientClick event to check stop this postback or not.
function onClientClickEvent() {
var text = document.getElementById('textDisplay');
var checkbox = document.getElementById('chkStopPostback');
text.value = "This is a client click";
if (checkbox.checked == true) {
return false;
}
else {
return true;
}
}
</script>
<style type="text/css">
.style1
{
width: 105px;
}
#textDisplay
{
width: 271px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width:100%;">
<tr>
<td class="style1">
<asp:Label ID="Label1" runat="server" Text="Stop postback:"></asp:Label>
</td>
<td>
<input id="chkStopPostback" type="checkbox" />Is stop?</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label2" runat="server" Text="Cause postback:"></asp:Label>
</td>
<td>
<asp:Button ID="btnCausePostback" runat="server" Text="Click me to get info"
OnClientClick="return onClientClickEvent()" οnclick="btnCausePostback_Click" />
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label3" runat="server" Text="Postback result:"></asp:Label>
</td>
<td>
<input id="textDisplay" readonly="readonly" type="text" runat="server" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
StopPostBack.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CSASPNETStopPostbackInJS
{
public partial class StopPostBack : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCausePostback_Click(object sender, EventArgs e)
{
// Postback code
textDisplay.Value += " This is a server click";
}
}
}