从用户控件调用父页面中的方法

时间:2022-10-19 22:28:31

I've a user control registered in an aspx page On click event of a button in the user control, how do i call a method which is there in the parent page's codebehind?

我在一个aspx页面中注册了一个用户控件,用户控件中的按钮点击事件,我如何调用父页面的codebehind中存在的一个方法?

Thanks.

谢谢。

9 个解决方案

#1


103  

Here is the classic example using events as suggested by Freddy Rios (C# from a web application project). This assumes that you want to use an existing delegate rather than make your own and you aren't passing anything specific to the parent page by event args.

下面是一个使用Freddy Rios(来自web应用项目的c#)建议的事件的经典示例。这假设您希望使用现有的委托而不是自己创建,并且不会通过事件args传递特定于父页面的任何内容。

In the user control's code-behind (adapt as necessary if not using code-behind or 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
}

In the page itself you subscribe to the event with something like this:

在页面本身中,您订阅了类似的事件:

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
    }

}

#2


12  

Cast the page as the specific page in your project:

将页面转换为项目中的特定页面:

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

#3


10  

I suggest you don't call the page method directly, as you would be tying your control to the specific page.

我建议您不要直接调用page方法,因为您将把控件绑定到特定的页面。

Instead expose an event, and have the page subscribe to it. It works for any number of pages, can more easily be used when the control is multiple times on a single page (perhaps even on a list) and is more in line with asp.control design.

相反,公开一个事件,并让页面订阅它。它适用于任意数量的页面,当控件在单个页面上(可能甚至是列表上)多次使用时更容易使用,并且更符合asp。控制设计。

#4


4  

Scott Allen has a useful article on event bubbling from a user control to the parent page, which elaborates on the answer provided by Stephen M. Redd:

Scott Allen有一篇关于事件从用户控件冒泡到父页面的有用文章,详细阐述了Stephen M. Redd提供的答案:

#5


4  

Follow good and appropriate approach,

遵循良好和适当的方法,

Use event and delegate concept make delegate as same signature as your method in parent page and then assign parent methad to it in parent page load event then call this delegate through event in user control.

使用事件和委托概念使委托与父页面中的方法具有相同的签名,然后在父页面装载事件中将父方法分配给它,然后通过用户控件中的事件调用此委托。

code sample and link is given below.

代码示例和链接如下所示。

//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);
 }
}

Read more details how it works (Reference) :-

详细阅读它是如何工作的(参考):-

Calling a method of parent page from user control

从用户控件调用父页面的方法

#6


2  

I want to do this scenario:

我想这样做:

  • Call LoadEditCategory method (parent method).
  • 调用LoadEditCategory方法(父方法)。
  • Parent method (LoadEditCategory) needs a int argument (CategoryID).
  • 父方法(LoadEditCategory)需要一个int参数(CategoryID)。
  • Child user control is RightControlPanel that is in same parent page folder.
  • 子用户控件是位于同一父页面文件夹中的RightControlPanel。

Child User control

儿童用户控件

1- Add a Action (_LoadEditCategory)

1-添加一个动作(_LoadEditCategory)

public Action<int> _LoadEditCategory = null;

公共行为 _LoadEditCategory = null;

<int> is int argument (CategoryID).

是int参数(CategoryID)。

2- Use this Action in button event (btnSavebutton name) like this:

2-在按钮事件(btnSavebutton name)中使用此操作如下:

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

Parent Page or parent user control

父页面或父用户控件

3- Add parent method

3 -添加父方法

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

4- Add this code when load child user control (RightControlPanel)

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);

   ...
 }

#7


0  

 //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 

#8


0  

I love Stephen M. Redd's answer and had to convert it to VB. Sharing it here. Suggested edits welcome.

我喜欢斯蒂芬·m·里德的答案,他必须把它转换成VB。在这里分享。建议编辑的欢迎。

In the user control's code-behind:

在用户控件的代码背后:

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

In the parent page subscribe to the event, so when the event is raised, your code will run here.

在父页面订阅事件,因此当事件被引发时,您的代码将在这里运行。

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

#9


-8  

You can use Session . Say when you click on a button in user control and when you want to call Parent page method then in event handler of button click set value as

您可以使用会话。当你点击用户控件中的按钮时,当你想调用父页面方法时,在按钮的事件处理程序中,点击设置值为

Session["CallParent"]="someValue";

as button will post back the page . On Page_Load event of Parent Page add it

as按钮将返回页面。在父页面的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;
    }
}

It is much more efficient

它的效率更高。

#1


103  

Here is the classic example using events as suggested by Freddy Rios (C# from a web application project). This assumes that you want to use an existing delegate rather than make your own and you aren't passing anything specific to the parent page by event args.

下面是一个使用Freddy Rios(来自web应用项目的c#)建议的事件的经典示例。这假设您希望使用现有的委托而不是自己创建,并且不会通过事件args传递特定于父页面的任何内容。

In the user control's code-behind (adapt as necessary if not using code-behind or 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
}

In the page itself you subscribe to the event with something like this:

在页面本身中,您订阅了类似的事件:

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
    }

}

#2


12  

Cast the page as the specific page in your project:

将页面转换为项目中的特定页面:

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

#3


10  

I suggest you don't call the page method directly, as you would be tying your control to the specific page.

我建议您不要直接调用page方法,因为您将把控件绑定到特定的页面。

Instead expose an event, and have the page subscribe to it. It works for any number of pages, can more easily be used when the control is multiple times on a single page (perhaps even on a list) and is more in line with asp.control design.

相反,公开一个事件,并让页面订阅它。它适用于任意数量的页面,当控件在单个页面上(可能甚至是列表上)多次使用时更容易使用,并且更符合asp。控制设计。

#4


4  

Scott Allen has a useful article on event bubbling from a user control to the parent page, which elaborates on the answer provided by Stephen M. Redd:

Scott Allen有一篇关于事件从用户控件冒泡到父页面的有用文章,详细阐述了Stephen M. Redd提供的答案:

#5


4  

Follow good and appropriate approach,

遵循良好和适当的方法,

Use event and delegate concept make delegate as same signature as your method in parent page and then assign parent methad to it in parent page load event then call this delegate through event in user control.

使用事件和委托概念使委托与父页面中的方法具有相同的签名,然后在父页面装载事件中将父方法分配给它,然后通过用户控件中的事件调用此委托。

code sample and link is given below.

代码示例和链接如下所示。

//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);
 }
}

Read more details how it works (Reference) :-

详细阅读它是如何工作的(参考):-

Calling a method of parent page from user control

从用户控件调用父页面的方法

#6


2  

I want to do this scenario:

我想这样做:

  • Call LoadEditCategory method (parent method).
  • 调用LoadEditCategory方法(父方法)。
  • Parent method (LoadEditCategory) needs a int argument (CategoryID).
  • 父方法(LoadEditCategory)需要一个int参数(CategoryID)。
  • Child user control is RightControlPanel that is in same parent page folder.
  • 子用户控件是位于同一父页面文件夹中的RightControlPanel。

Child User control

儿童用户控件

1- Add a Action (_LoadEditCategory)

1-添加一个动作(_LoadEditCategory)

public Action<int> _LoadEditCategory = null;

公共行为 _LoadEditCategory = null;

<int> is int argument (CategoryID).

是int参数(CategoryID)。

2- Use this Action in button event (btnSavebutton name) like this:

2-在按钮事件(btnSavebutton name)中使用此操作如下:

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

Parent Page or parent user control

父页面或父用户控件

3- Add parent method

3 -添加父方法

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

4- Add this code when load child user control (RightControlPanel)

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);

   ...
 }

#7


0  

 //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 

#8


0  

I love Stephen M. Redd's answer and had to convert it to VB. Sharing it here. Suggested edits welcome.

我喜欢斯蒂芬·m·里德的答案,他必须把它转换成VB。在这里分享。建议编辑的欢迎。

In the user control's code-behind:

在用户控件的代码背后:

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

In the parent page subscribe to the event, so when the event is raised, your code will run here.

在父页面订阅事件,因此当事件被引发时,您的代码将在这里运行。

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

#9


-8  

You can use Session . Say when you click on a button in user control and when you want to call Parent page method then in event handler of button click set value as

您可以使用会话。当你点击用户控件中的按钮时,当你想调用父页面方法时,在按钮的事件处理程序中,点击设置值为

Session["CallParent"]="someValue";

as button will post back the page . On Page_Load event of Parent Page add it

as按钮将返回页面。在父页面的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;
    }
}

It is much more efficient

它的效率更高。