开发者

ASP.NET Update Elements In Master?

开发者 https://www.devze.com 2023-03-22 00:54 出处:网络
I\'m a web designer so I rarely get my hands dirty in .NET code.I\'m doing a bit of light coding repurposing some code from one area of a site for another.How to target elements in a master?I have the

I'm a web designer so I rarely get my hands dirty in .NET code. I'm doing a bit of light coding repurposing some code from one area of a site for another. How to target elements in a master? I have the following in a page that is calling a master that contains lblError and pnlError...

    public void AddError(string error)
    {
        if (error != "")开发者_运维技巧
        {
            lblError.Text = error;
            pnlError.Visible = true;
        }
    }

I'm getting an error that says the items do not exist in the current context. How to I tell it to look for the elements within the master?


You can use the following in the code behind for any page:

var masterpage = this.Master as MyMasterPageClass;

MYMasterPageClass is the type of your master page, casting to this will allow you to access specific properties of your page.

Also note that you will not be able to access controls directly as they are private. You can, however, make a public property in the masterpage's code behind that allows you to change their values.

public partial class MYMasterPageClass : System.Web.UI.MasterPage
{
    public string Error
    {
        get { return lblError.Text;}
        set { lblError.Text = value; }
    }
}


So I don't know if it is the cleanest way to do it, but the following worked for me...

   public void AddError(string error)
    {
        if (error != "")
        {
            Label mpLabel = (Label)Page.Master.FindControl("lblError");
            mpLabel.Text = error;

            Panel mpPanel = (Panel)Page.Master.FindControl("pnlError");
            mpPanel.Visible = true;
        }
    }
0

精彩评论

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