【问题标题】:Accessing Master Page Controls in Non master page?在非母版页中访问母版页控件?
【发布时间】:2013-07-26 03:15:17
【问题描述】:

在 asp.net 中,如何访问非母版页中的母版页控件?

【问题讨论】:

  • 您正在使用具有控件的母版页呈现的视图?

标签: asp.net master-pages


【解决方案1】:

您可以将母版页作为当前页面上的属性访问。但是,母版页上的控件受到保护,因此您无法直接访问它们。但是您可以使用FindControl(string name) 访问它们。您需要使用的代码取决于控件是在内容占位符内部还是外部。

// Gets a reference to a TextBox control inside a ContentPlaceHolder
ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder = 
    (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(mpContentPlaceHolder != null)
{
    mpTextBox = (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
    if(mpTextBox != null)
    {
        mpTextBox.Text = "TextBox found!";
    }
}

// Gets a reference to a Label control that is not in a 
// ContentPlaceHolder control
Label mpLabel = (Label) Master.FindControl("masterPageLabel");
if(mpLabel != null)
{
    Label1.Text = "Master page label = " + mpLabel.Text;
}

【讨论】:

    【解决方案2】:

    将此添加到您的网页以访问母版页的内容Master Page : programatically access

    <%@ MasterType virtualpath="Your MasterPath" %>
    

    你可以这样做(替代方式)

    MasterPage mstr 
    Label lbl
    mstr = Page.Master
    If (mstr.ID == "yourMasterIDString")
    {
         lbl = mstr.FindControl("lblBar")
            If (lbl !=null)
              {
                    lbl.Text = "Do some Logic"
              }
    }
    

    【讨论】:

      【解决方案3】:

      使用可以

      TextBox txt1 = (TextBox)this.Master.FindControl("MytxtBox");
      txt1.Text="Content Changed from content page";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多