开发者

Call Function From UserControl on ASPX From UserControl on MasterPage

开发者 https://www.devze.com 2023-02-07 13:25 出处:网络
I have MainLayout.master that has UC_Menu.ascx on it. I have a page named Customer.aspx that uses MainLayout.master. Customer.aspx also contains a UserControl named UC_Details.a开发者_Go百科scx.

I have MainLayout.master that has UC_Menu.ascx on it.

I have a page named Customer.aspx that uses MainLayout.master. Customer.aspx also contains a UserControl named UC_Details.a开发者_Go百科scx.

How can I have UC_Menu.ascx call a function that is in UC_Details.ascx with this scenario?

I've seen a few similar examples, but none that match this type of layout.


In my opinion you should raise event from UC_Menu.ascx, then handle it in Master page and raise event again from Master page already. Finally you can intercept event with event handler in Customer.aspx and call function from UC_Details.ascx.

So, the code for this issue should be:

1) Inside your UC_Menu.ascx.vb raise an event:

Partial Class UserControls_UC_Menu
    Inherits System.Web.UI.UserControl

    Public Event SomethingChanged As EventHandler

    Public Sub SomethingHappend()
        RaiseEvent SomethingChanged(Me, EventArgs.Empty)
    End Sub

End Class

2) In Master page catch event and raise it to Customer.aspx

Public Event SomethingChanged As EventHandler

Private Sub UC_MenuInstance_SomethingChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UC_Menu.SomethingChanged
     RaiseEvent Me.SomethingChanged(Me, EventArgs.Empty)
End Sub

3) Define in Customer.aspx markup after page directive:

<%@ MasterType VirtualPath="~/MasterPages/MainLayout.master" %>

4) Inside UC_Details.ascx.vb define some method that should be called:

Public Sub DoWork()
   'Do some work here
End Sub

5) Place into Customer.aspx.vb:

' Add handler for Master page event
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    AddHandler Me.Master.SomethingChanged, AddressOf MasterEventHandler
End Sub

' Call UC_Details user control function here
Private Sub MasterEventHandler(ByVal source As Object, ByVal e As EventArgs)
        UC_DetailsInstance.DoWork()
    End Sub


Interesting scenario. Have the page implement an interface:

public interface IDetailsPage
{
   UC_Details DetailsControl { get; }
}

The page would then directly expose the control of the property. In UC_Menu, use:

if (this.Page is IDetailsPage)
    ((IDetailsPage)this.Page).DetailsControl.CallMethod();

HTH.


You should find UC_Menu on master page, and call it's method:

var c = (UC_Menu) Master.FindControl("UC_Menu");
if (c != null)
{
    c.CallMethod();
}

Checkout this article.

0

精彩评论

暂无评论...
验证码 换一张
取 消