摘要:避免使用者重複按下button
在網頁上我們經常會透過表單與使用者進行互動。
不過因為網路回應有慢有快,可能會連續送出表單的資料,結果造成資料的重複輸入。
asp.net有一個小技巧的方法可以簡單的防護這樣的情形發生。
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Button1.Attributes["onclick"] = "this.disabled = true;" +
Page.ClientScript.GetPostBackEventReference(Button1, "");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
}
{
if (!Page.IsPostBack)
{
Button1.Attributes["onclick"] = "this.disabled = true;" +
Page.ClientScript.GetPostBackEventReference(Button1, "");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
}
在page load的時候替button加入一個onclick的屬性,設定按下button之後便disable自己,再去觸發 form submit。
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTQ2OTkzNDMyMQ9kFgICAw9kFgICAQ8PZBYCHgdvbmNsaWNrBS90aGlzLmRpc2FibGVkID0gdHJ1ZTtfX2RvUG9zdEJhY2soJ0J1dHRvbjEnLCcnKWRkfWX8S2VxKVGYt+J8gJXShAbhPv4=" />
</div>
<script type="text/javascript">
<!--
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
// -->
</script>
<div>
<input type="submit" name="Button1" value="Button" onclick="this.disabled = true;__doPostBack('Button1','');" id="Button1" />
</div>
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTQ2OTkzNDMyMQ9kFgICAw9kFgICAQ8PZBYCHgdvbmNsaWNrBS90aGlzLmRpc2FibGVkID0gdHJ1ZTtfX2RvUG9zdEJhY2soJ0J1dHRvbjEnLCcnKWRkfWX8S2VxKVGYt+J8gJXShAbhPv4=" />
</div>
<script type="text/javascript">
<!--
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
// -->
</script>
<div>
<input type="submit" name="Button1" value="Button" onclick="this.disabled = true;__doPostBack('Button1','');" id="Button1" />
</div>
<div>
這樣就可以避免使用者重複按下button了。
---------------
這是簽名檔,I love Dotblogs