Pass Data into User Control on Master Page from Sub Page

佐手、 提交于 2019-12-10 11:49:27

问题


I have a user control on the master page and I would like to pass in a value into that user control from the subpage, how would I be able to pass the values?

This control is in the master page

<%@ Register TagPrefix="test" TagName="Data" Src="controls/TEST.ascx" %>

This code variable is within the user control

public partial class Controls_TEST : System.Web.UI.UserControl
{
    private string _Title;
    public string Title
    {
        get { return _Title; }
        set { _Title = value; }
    }
}

Code within the subpage

public partial class sub_page : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
         Controls_Test m = LoadControl("~/Controls/TEST.ascx");
         m.Title = "TEST";
    }
}

Note the sample code within subpage does not work because it cannot find that user control within the subpage.

I've tried Page.Master.FindControl and it also does not work for me. PLease help.


回答1:


Use properties to communicate from your Page to your MasterPage and use properties to communicate from your MasterPage to the UserControl.

To get a reference to the control in your MasterPage you should provide a public property that returns it:

For example(in MasterPage):

public Controls_Test MyControl
{
     get
     {
         return Controls_TEST1;
     }
}

And you can call this property from one of your ContentPages in this way(f.e. if your master's type is named "SiteMaster"):

protected void Page_Load(object sender, EventArgs e)
{
    ((SiteMaster)Page.Master).MyControl.Title = "TEST";
}

As a rule of thumb: the more you encapsulate your controls, the more robust ,failsafe, maintanable and extendable your code will be.

Hence it would be better to provide only access to the Title rather than to the whole UserControl.

In MasterPage:

public String Title
{
     get
     {
         return Controls_TEST1.Title;
     }
    set
    {
        Controls_TEST1.Title = value;
    }
}

In the ContentPage:

((SiteMaster)Page.Master).Title = "TEST";

On this way you could change the logic and controls in your UserControl and MasterPage without having problems in your pages that already have accessed the UserControl directly.



来源:https://stackoverflow.com/questions/9640286/pass-data-into-user-control-on-master-page-from-sub-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!