2008-10-09 79 views
11

在c#中,如何檢查頁面加載方法中是否單擊了鏈接按鈕?ASP.NET:檢查page_load中的單擊事件

我需要知道在點擊事件被觸發之前它是否被點擊。

+0

如果你的代碼是在OnClick事件依賴,那麼你可以把在那個特定的代碼OnPageRender覆蓋(而不是Page_Load),因爲它會在OnClick事件處理程序之後觸發。 – snumpy 2015-08-12 13:32:01

回答

19
if(IsPostBack) 
{ 
    // get the target of the post-back, will be the name of the control 
    // that issued the post-back 
    string eTarget = Request.Params["__EVENTTARGET"].ToString(); 
} 
+0

你測試過了嗎?應該有兩個引導斜線 - 「__EVENTTARGET」 – 2008-10-09 18:39:11

2

檢查請求參數__EVENTTARGET的值,看看它是否是問題鏈接按鈕的ID。

2

按鈕的UniqueID將在的Request.Form [ 「__ EVENTTARGET」]

2

如果沒有work.Try UseSubmitBehavior="false"

1

基於公認的答案和鐵甲鋼拳這個的答案可能是一個更完整的答案。

首先添加到.aspx一個按鈕是這樣的:

<asp:Button id="btnExport" runat="server" Text="Export" UseSubmitBehavior="false"/> 

然後在Page_Load方法:

if(IsPostBack){ 
    var eventTarget = Request.Params["__EVENTTARGET"] 
    // Then check for the id but keep in mind that the name could be 
    // something like ctl00$ContainerName$btnExport 
    // if the button was clicked or null so take precautions against null 
    // ... so it could be something like this 
    var buttonClicked = eventTarget.Substring(eventTarget.LastIndexOf("$") + 1).Equals("btnExport") 

} 
0

我剛剛得到了同樣的麻煩,已經做的一些邏輯判斷Page_Load方法來處理不同的事件(哪個按鈕被點擊)。

我意識到手臂得到如下例子。

前端ASPX源代碼(我有ID的F2,F3,F6,F12的按鈕。

<Button Style="display: none" ID="F2" runat="server" Text="F2:Cancel" OnClientClick="SeiGyo(this)" OnClick="F2_Click" /> 
    <Button Style="display: none" ID="F3" runat="server" Text="F3:Return" OnClientClick="SeiGyo(this)" OnClick="F3_Click" /> 
    <Button Style="display: none" ID="F6" runat="server" Text="F6:Run" OnClientClick="SeiGyo(this)" OnClick="F6_Click" /> 
    <Button Style="display: none" ID="F12" runat="server" Text="F12:Finish" OnClientClick="SeiGyo(this)" OnClick="F12_Click" /> 

後端aspx.cs源代碼,我需要做的是判斷哪個按鈕Page_Load中被觸發時被點擊了。這似乎有點愚蠢,但作品。我希望這將有助於其他一些

Dictionary<string, string> dic = new Dictionary<string, string>(); 
foreach(var id in new string[]{"F2","F3","F6","F12"}) 
{ 
     foreach (var key in Request.Params.AllKeys) 
        { 
         if (key != null && key.ToString().Contains(id)) 
          dic.Add(id, Request[key.ToString()].ToString()); 
        } 
} 
相關問題