使用母版页时访问 C# 中的内容控件

发布于 2024-07-25 22:43:10 字数 606 浏览 5 评论 0原文

大家好,

我正在 ASP.NET 中构建一个页面,并在此过程中使用母版页。

我的母版页中有一个内容占位符名称“cphBody”,它将包含该母版页作为母版页的每个页面的正文。

在 ASP.NET 网页中,我有一个 Content 标记(引用“cphBody”),其中还包含一些控件(按钮、Infragistics 控件等),并且我想在 CodeBehind 文件中访问这些控件。 但是,我无法直接执行此操作(this.myControl ...),因为它们嵌套在 Content 标记中。

我找到了 FindControl 方法的解决方法。

ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder) Master.FindControl("cphBody");
ControlType myControl = (ControlType) contentPlaceHolder.FindControl("ControlName");

效果很好。 但是,我怀疑这不是一个很好的设计。 你们知道一种更优雅的方法吗?

谢谢你!

纪尧姆·热尔韦.

Good day everyone,

I am building a page in ASP.NET, and using Master Pages in the process.

I have a Content Place Holder name "cphBody" in my Master Page, which will contain the body of each Page for which that Master Page is the Master Page.

In the ASP.NET Web page, I have a Content tag (referencing "cphBody") which also contains some controls (buttons, Infragistics controls, etc.), and I want to access these controls in the CodeBehind file. However, I can't do that directly (this.myControl ...), since they are nested in the Content tag.

I found a workaround with the FindControl method.

ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder) Master.FindControl("cphBody");
ControlType myControl = (ControlType) contentPlaceHolder.FindControl("ControlName");

That works just fine. However, I am suspecting that it's not a very good design. Do you guys know a more elegant way to do so?

Thank you!

Guillaume Gervais.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夕色琉璃 2024-08-01 22:43:10

我会尽量避免使用 FindControl,除非别无选择,而且通常有更简洁的方法。

如何在子页面顶部包含母版页的路径

<%@ MasterType VirtualPath="~/MasterPages/PublicUI.Master" %>

,这将允许您直接从母版页代码后面调用代码。

然后,从后面的母版页代码中,您可以使属性返回您的控件,或者使母版页上的方法获取您的控件等。

public Label SomethingLabel
{
    get { return lblSomething; }
}
//or
public string SomethingText
{
    get { return lblSomething.Text; }
    set { lblSomething.Text = value; }
}

指的是母版页上的标签用法

<asp:Label ID="lblSomething" runat="server" />

Master.SomethingLabel.Text = "some text";
//or
Master.SomethingText = "some text";

I try and avoid FindControl unless there is no alternative, and there's usually a neater way.

How about including the path to your master page at the top of your child page

<%@ MasterType VirtualPath="~/MasterPages/PublicUI.Master" %>

Which will allow you to directly call code from your master page code behind.

Then from your master page code behind you could make a property return your control, or make a method on the master page get your control etc.

public Label SomethingLabel
{
    get { return lblSomething; }
}
//or
public string SomethingText
{
    get { return lblSomething.Text; }
    set { lblSomething.Text = value; }
}

Refers to a label on the master page

<asp:Label ID="lblSomething" runat="server" />

Usage:

Master.SomethingLabel.Text = "some text";
//or
Master.SomethingText = "some text";
拍不死你 2024-08-01 22:43:10

Rick Strahl 在这里有一个很好的解释(和示例代码) - http://www .west-wind.com/Weblog/posts/5127.aspx

Rick Strahl has a good explanation (and sample code) here - http://www.west-wind.com/Weblog/posts/5127.aspx

随梦而飞# 2024-08-01 22:43:10

没什么可做的不同。 只需在子页面上编写此代码即可访问母版页标签控件。

Label lblMessage = new Label();
lblMessage = (Label)Master.FindControl("lblTest");
lblMessage.Text = DropDownList1.SelectedItem.Text;

Nothing to do different. Just write this code on child page to access the master page label control.

Label lblMessage = new Label();
lblMessage = (Label)Master.FindControl("lblTest");
lblMessage.Text = DropDownList1.SelectedItem.Text;
┈┾☆殇 2024-08-01 22:43:10

我使用此代码递归访问文件:

    /// <summary>
    /// Recursively iterate through the controls collection to find the child controls of the given control
    /// including controls inside child controls. Return all the IDs of controls of the given type 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="controlType"></param>
    /// <returns></returns>
    public static List<string> GetChildControlsId(Control control, Type controlType)
    {
        List<string> FoundControlsIds = new List<string>();
        GetChildControlsIdRecursive(FoundControlsIds, control, controlType);

        // return the result as a generic list of Controls
        return FoundControlsIds;
    }

    public static List<string> GetChildControlsIdRecursive(List<string> foundControlsIds, Control control, Type controlType)
    {
        foreach (Control c in control.Controls)
        {
            if (controlType == null || controlType.IsAssignableFrom(c.GetType()))
            {
                // check if the control is already in the collection
                String FoundControl = foundControlsIds.Find(delegate(string ctrlId) { return ctrlId == c.ID; });

                if (String.IsNullOrEmpty(FoundControl))
                {
                    // add this control and all its nested controls
                    foundControlsIds.Add(c.ID);
                }
            }

            if (c.HasControls())
            {
                GetChildControlsIdRecursive(foundControlsIds, c, controlType);
            }
        }

I use this code for acess to files recursively:

    /// <summary>
    /// Recursively iterate through the controls collection to find the child controls of the given control
    /// including controls inside child controls. Return all the IDs of controls of the given type 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="controlType"></param>
    /// <returns></returns>
    public static List<string> GetChildControlsId(Control control, Type controlType)
    {
        List<string> FoundControlsIds = new List<string>();
        GetChildControlsIdRecursive(FoundControlsIds, control, controlType);

        // return the result as a generic list of Controls
        return FoundControlsIds;
    }

    public static List<string> GetChildControlsIdRecursive(List<string> foundControlsIds, Control control, Type controlType)
    {
        foreach (Control c in control.Controls)
        {
            if (controlType == null || controlType.IsAssignableFrom(c.GetType()))
            {
                // check if the control is already in the collection
                String FoundControl = foundControlsIds.Find(delegate(string ctrlId) { return ctrlId == c.ID; });

                if (String.IsNullOrEmpty(FoundControl))
                {
                    // add this control and all its nested controls
                    foundControlsIds.Add(c.ID);
                }
            }

            if (c.HasControls())
            {
                GetChildControlsIdRecursive(foundControlsIds, c, controlType);
            }
        }
佞臣 2024-08-01 22:43:10

嗨,我只是想分享我的解决方案,发现这适用于访问 << 内部的“控件”。 asp:面板> 它位于“ContentPage”上,但来自“MasterPage”后面的 C# 代码。 希望它能帮助一些人。

  1. 添加一个< asp:面板> 在您的 ContentPage 中添加 ID="PanelWithLabel" 和 runat="server"。

  2. 在面板内,添加

    asp:标签> 使用 ID="MyLabel" 进行控制。

  3. 在母版页代码隐藏中编写(或复制/粘贴以下内容)一个函数,如下所示:(这将访问面板内的标签控件,这些控件都位于内容页上,从母版页代码隐藏并更改它的文本是母版页上文本框的文本:)

    protected void onButton1_click(object sender, EventArgs e) 
      { 
      // 在内容页面上找到一个面板并从我后面的母版页代码访问其控件(标签、文本框等)// 
      System.Web.UI.WebControls.Panel pnl1; 
      pnl1 = (System.Web.UI.WebControls.Panel)MainContent.FindControl("PanelWithLabel"); 
      if (pnl1 != null) 
       { 
          System.Web.UI.WebControls.Label lbl = (System.Web.UI.WebControls.Label)pnl1.FindControl("MyLabel"); 
          lbl.Text = MyMasterPageTextBox.Text; 
       } 
      } 
      

Hi just thought i'd share my solution, found this works for accessing a 'Control' that is inside an < asp:Panel> which is on a 'ContentPage', but from C# code-behind of the 'MasterPage'. Hope it helps some.

  1. add an < asp:Panel> with an ID="PanelWithLabel" and runat="server" to your ContentPage.

  2. inside the Panel, add an < asp:Label> control with ID="MyLabel".

  3. write (or copy / paste the below) a function in your MasterPage Code-behind as follows: (this accesses the label control, inside the Panel, which are both on the ContentPage, from the Master page code-behind and changes its text to be that of a TextBox on the Master page :)

    protected void onButton1_click(object sender, EventArgs e)
    {
    // find a Panel on Content Page and access its controls (Labels, TextBoxes, etc.) from my master page code behind //
    System.Web.UI.WebControls.Panel pnl1;
    pnl1 = (System.Web.UI.WebControls.Panel)MainContent.FindControl("PanelWithLabel");
    if (pnl1 != null)
     {
        System.Web.UI.WebControls.Label lbl = (System.Web.UI.WebControls.Label)pnl1.FindControl("MyLabel");
        lbl.Text = MyMasterPageTextBox.Text;
     }
    }
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文