有的時候想在用戶端觸發伺服器端控制項的CLICK事件時我們這麼寫__doPostBack("id",""),但是為什麼有的時候會失效呢?
通過查看用戶端原始碼發現頁面中沒有產生__doPostBack()這段JS.
原來ASP.NET要產生__doPostBack的前提是伺服器控制項要有AutoPostBack = true 並且 控制項要啟用才行
如果我們沒有上面的條件但又想要頁面產生__doPostBack怎麼辦呢?
解決方案:
原來Page裡面有個方法是GetPostBackEventReference,這個就可以產生__doPostBack,它有兩個版本
1.取得用戶端指令碼函式的參考,(這個參考會) 在叫用時讓伺服器回傳網頁。
public string GetPostBackEventReference(Control);
2.取得用戶端指令碼函式的參考,(這個參考會) 在叫用時讓伺服器回傳網頁。這個方法同時也傳遞參數給在伺服器上執行回傳處理的伺服器控制項。public string GetPostBackEventReference(Control, string);
如果只想產生__doPostBack,則只用第一種就行了,
第二種帶參數的,可以通過判斷所帶入的參數做不同的動作,
下面舉個例子.
前台頁面
有個伺服器控制項
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
一個用戶端控制項用來觸發伺服器端
<a href="#" onclick="document.getElementById('Button1').click()">觸發伺服器端按鈕事件</a>
(2)
利用GetPostBackEventReference給用戶端產生__doPostBack()
前台
<a href="#" onclick="<%=PostBack()%>">觸發伺服器端按鈕事件</a>
後台
protected string PostBack()
{
return this.Page.GetPostBackEventReference(this.Button1,"haha");
}
通過__EVENTARGUMENT="haha"可以判斷是不是點了那個連結的PostBack
把Button1的按鈕事件這麼寫:
if(Request["__EVENTARGUMENT" ]=="haha")
{
Response.Write("這個是連結的PostBack");
}
else
{
Response.Write("這個不是連結的PostBack");
}
以下這個是微軟MSDN上的例子,看起來也不錯
public class MyControl : Control, IPostBackEventHandler
{
// Create an integer property that is displayed when
// the page that contains this control is requested
// and save it to the control's ViewState property.
public int Number
{
get
{
if ( ViewState["Number"] !=null )
return (int) ViewState["Number"];
return 50;
}
set
{
ViewState["Number"] = value;
}
}
// Implement the RaisePostBackEvent method from the
// IPostBackEventHandler interface. If 'inc' is passed
// to this method, it increases the Number property by one.
// If 'dec' is passed to this method, it decreases the
// Number property by one.
public void RaisePostBackEvent(string eventArgument)
{
if ( eventArgument == "inc" )
Number = Number + 1;
if ( eventArgument == "dec" )
Number = Number - 1;
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
protected override void Render(HtmlTextWriter writer)
{
// Converts the Number property to a string and
// writes it to the containing page.
writer.Write("The Number is " + Number.ToString() + " (" );
// Uses the GetPostBackEventReference method to pass
// 'inc' to the RaisePostBackEvent method when the link
// this code creates is clicked.
writer.Write("<a href=\"javascript:" + Page.GetPostBackEventReference(this,"inc") + "\">Increase Number</a>");
writer.Write(" or ");
// Uses the GetPostBackEventReference method to pass
// 'dec' to the RaisePostBackEvent method when the link
// this code creates is clicked.
writer.Write("<a href=\"javascript:" + Page.GetPostBackEventReference(this,"dec") + "\">Decrease Number</a>");
}
}