簡體   English   中英

從用戶控件調用父頁面中的方法

[英]Calling a method in parent page from user control

我在aspx頁面中注冊了一個用戶控件在用戶控件中按鈕的單擊事件中,我如何調用父頁面的代碼隱藏中存在的方法?

謝謝。

這是 Freddy Rios 建議的使用事件的經典示例(來自 web 應用程序項目的 C#)。 這假設您想要使用現有委托而不是自己創建委托,並且您沒有通過事件參數傳遞任何特定於父頁面的內容。

在用戶控件的代碼隱藏中(如果不使用代碼隱藏或 C#,則根據需要進行調整):

public partial class MyUserControl : System.Web.UI.UserControl
{
    public event EventHandler UserControlButtonClicked;

    private void OnUserControlButtonClick()
    {
        if (UserControlButtonClicked != null)
        {
            UserControlButtonClicked(this, EventArgs.Empty);
        }
    }

    protected void TheButton_Click(object sender, EventArgs e)
    {
        // .... do stuff then fire off the event
        OnUserControlButtonClick();
    }

    // .... other code for the user control beyond this point
}

在頁面本身中,您使用以下內容訂閱事件:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // hook up event handler for exposed user control event
        MyUserControl.UserControlButtonClicked += new  
                    EventHandler(MyUserControl_UserControlButtonClicked);
    }
    private void MyUserControl_UserControlButtonClicked(object sender, EventArgs e)
    {
        // ... do something when event is fired
    }

}

將頁面轉換為項目中的特定頁面:

((MyPageName)this.Page).CustomMethod()

我建議您不要直接調用 page 方法,因為您會將控件綁定到特定頁面。

而是公開一個事件,並讓頁面訂閱它。 它適用於任意數量的頁面,當控件在單個頁面上多次(甚至可能在列表上)時更容易使用,並且更符合 asp.control 設計。

Scott Allen有一篇關於從用戶控件到父頁面的事件冒泡的有用文章,詳細闡述了Stephen M. Redd提供的答案:

遵循良好和適當的方法,

使用事件和委托概念使委托與父頁面中的方法具有相同的簽名,然后在父頁面加載事件中為其分配父方法,然后通過用戶控件中的事件調用此委托。

代碼示例和鏈接如下。

//Parent Page aspx.cs part

 public partial class getproductdetails : System.Web.UI.Page
 {
  protected void Page_Load(object sender, EventArgs e)
  {
   ucPrompt.checkIfExist += new uc_prompt.customHandler(MyParentMethod);
  }

  bool MyParentMethod(object sender)
  {
   //Do Work
  }
}

//User control parts
public partial class uc_prompt : System.Web.UI.UserControl
{
 protected void Page_Load(object sender, EventArgs e)
 {
 }

 public delegate bool customHandler(object sender);
 public event customHandler checkIfExist;
 protected void btnYes_Click(object sender, EventArgs e)
 {
  checkIfExist(sender);
 }
}

閱讀更多詳細信息它是如何工作的(參考):-

從用戶控件調用父頁面的方法

我想做這個場景:

  • 調用LoadEditCategory方法(父方法)。
  • 父方法 ( LoadEditCategory ) 需要一個int參數 ( CategoryID )。
  • 子用戶控件是位於同一父頁面文件夾中的RightControlPanel

子用戶控制

1-添加一個Action_LoadEditCategory

public Action<int> _LoadEditCategory = null;

<int>int參數( CategoryID )。

2- 在按鈕事件( btnSave按鈕名稱)中使用此Action ,如下所示:

void btnSave_Click(object sender, EventArgs e)
{
    //123 is test integer for CategoryID
    _LoadEditCategory(123);        
}

父頁面或父用戶控件

3-添加父方法

 private void LoadEditCategory(int CategoryID)
    {
     // CategoryID is 123 in my example
     //Do some things with CategoryID
    }

4-加載子用戶控件時添加此代碼( RightControlPanel

//Load child user control
RightControlPanel si = this.LoadControl(this.ControlPath + "RightControlPanel.ascx") as RightControlPanel;
if (si != null) 
 {
   ...

   //For call parent method in child user control
   si._LoadEditCategory = c => LoadEditCategory(c);

   ...
 }
 //c#
 //In parent page
 public void test(string S)
 {
    Label1.Text = S;
  }

 //In user control
 protected void Button1_Click(object sender, System.EventArgs e)
 {
 //Calling "test method" of parent page  from user control  
 ((object)this.Page).test("Hello!!");
 }

 'VB.Net 
'In parent page
 Sub test(ByVal S As String)
    Label1.Text = S
 End Sub

 'In user control
  Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
  'Calling "test method" of parent page  from user control  
  DirectCast(Me.Page, Object).test("Hello!!")
  End Sub 

我喜歡 Stephen M. Redd 的回答,不得不將其轉換為 VB。 在這里分享。 歡迎提出修改建議。

在用戶控件的代碼隱藏中:

Public Class MyUserControl
    Inherits System.Web.UI.UserControl

    'expose the event publicly
    Public Event UserControlButtonClicked As EventHandler 

    'a method to raise the publicly exposed event
    Private Sub OnUserControlButtonClick()

        RaiseEvent UserControlButtonClicked(Me, EventArgs.Empty)

    End Sub

    Protected Sub lbtnApplyChanges_Click(sender As Object, e As EventArgs) Handles lbtnApplyChanges.Click

        'add code to run here, then extend this code by firing off this event
        'so it will trigger the public event handler from the parent page, 
        'and the parent page can hanlde it

        OnUserControlButtonClick()

    End Sub

End Class

在父頁面訂閱事件,因此當事件引發時,您的代碼將在此處運行。

Public Class SalesRecord
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'hook up event handler for exposed user control event to handle this
        AddHandler MyUserControl.UserControlButtonClicked, AddressOf MyUserControl_UserControlButtonClicked

    End Sub

    ''' <summary>
    ''' code to run when user clicks 'lbtnApplyChanges' on the user control
    ''' </summary>

    Private Sub MyUserControl_UserControlButtonClicked()

        'this code will now fire when lbtnApplyChanges_Click executes

    End Sub

End Class

我在這里發布了一些有用的東西: 訪問控制>頁面>主嵌套>主

或者如果你想訪問一個控件,你也可以這樣做:

更新父頁面 父頁面有一個名為“UpdatePanel1”的更新面板

控制

UpdatePanel onParent1 = (UpdatePanel)Parent.FindControl("UpdatePanel1");
onParent1.Update();

您可以使用 Session。 說當您單擊用戶控件中的按鈕以及想要調用父頁面方法時,然后在按鈕單擊的事件處理程序中將值設置為

Session["CallParent"]="someValue";

作為按鈕將回發頁面。 在父頁面的 Page_Load 事件上添加它

protected void Page_Load(object sender,EventArgs e)
{
   if(Session["CallParent"]!=null)
   {
      // here call the Parent Page method 
      Method1();
      // now make the session value null
     Session["CallParent"]=null;
    }
}

它效率更高

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM