Access Master Page/Child Page Controls from My Class
I have a div on my master page and I want to use it for showing page errors. I have an error display class and it works fine. My problem is that in some instances, the 开发者_Go百科error gets displayed even before the tag resulting in (non)-display of the message. This is mostly with code that has response.redirect.
I want to counter this by having the error shown on a div within my master page (hoep it helps).
How can I access <div id="errorSegment" runat="server">
?
You can use the FindControl
method on any class that inherits from System.Web.UI.Control
. This includes Master Pages, Pages and UserControls. For instance, from a page class, you could do:
HtmlGenericControl errorDiv = (HtmlGenericControl)Master.FindControl("errorSegment");
The other thing to remember about using FindControl
is that controls in an ASP page are arranged in a control tree structure. This means that you need to call FindControl
on the right node in the tree (typically the Page or the MasterPage).
You can create a public property on your master page that exposes the div:
public HtmlGenericControl ErrorSegment
{
get { return errorSegment; }
}
Your pages that use that master page will have a reference to the master page through the Page.Master property, but the type of this property will be the base master page class, not your specific class with the public property. Therefore, add this tag to your pages' aspx markup to generate a Master property with your specific master page type:
<%@ MasterType VirtualPath="~/AccessManager.Master" %>
You can then access it from the page using the page's reference to the master page:
this.Master.ErrorSegment
Your MasterPage can have a public property to expose the div:
public HtmlGenericControl ErrorSegment
{
get { return errorSegment; }
}
As you will probably use ErrorSegment property on many pages it might be good to declare a base class for your pages and include the following declaration:
public class MyBasePage : System.Web.UI.Page
{
// This declaration "forces" the Master property to be of your preferred type.
public new MyMasterPage Master
{
get
{
return ((MyMasterPage)(base.Master));
}
}
}
Now you can access ErrorSegment on any page deriving from MyBasePage (also indirectly) with the following code:
this.Master.ErrorSegment
The advantage of this solution over the <%@ MasterType %>
tag is that you can move this declaration along your class hierachy and then access the ErrorSegment on any level that you need.
精彩评论