I fell over the following exercise:
You got a masterpage "custom.master". You then have a nested masterpage
"nested.master". You then have a content page that uses the
nested.master. How do you access a property of custom.master from the
content page.
The right answer should be "parent.master.propertyname". But I would expect "master.master.propertyname" as the parent of a contentpage should not be a masterpage.
As everyone sais, "parent.master" is the right one I am probably wrong. Can anyone provide an explanaition or a link, why parent.master would be the right choice?
The following code will give you the desired result
this.Master.Master.PropertyName
Thanks,
Abhishek S.
I know this is an old question but I came across a need for doing this recently and thought I'd add my solution which works for any master page nesting level and also returns the master as your specific type so that you can access properties on it instead of just a System.Web.UI.MasterPage as this.Master.Master would give:
public static T GetRootMasterPage<T>(MasterPage master) where T : MasterPage
{
if (master != null)
{
if (master.Master == null) // We've found the root
{
if (master is T)
{
return master as T;
}
else
{
throw new Exception($"GetRootMasterPage<T>: Could not find MasterPage of type {typeof(T)}");
}
}
else // We're on a nested master
{
return GetRootMasterPage<T>(master.Master);
}
}
return null;
}
Usage:
var root = GetRootMasterPage<Root>(this.Master);
// ...
// Do whatever with your 'Root' master page type
Related
My question is similar to Access to PartialCachingControl.CachedControl before Add it but since i cannot add the control to page before setting control attributes im still having problems
I have a UserControl with a public property called "Content" which i would like to cache. On the UserControl ive added:
<%# OutputCache Duration="60" VaryByParam="none" %>
Before adding the Cache Attribute i used to load the controls as followed
public static Control DocumentWidget (System.Web.UI.Page currentPage, Comito.LokalPortalen.Domain.Entity.CMS.Content.Content content)
{
Comito.LokalPortalen.FrontEndShared.Controls.Document.Widget documentWidget = (FrontEndShared.Controls.Document.Widget)currentPage.LoadControl("/FrontEndShared/Controls/Document/Widget.ascx");
if (documentWidget != null)
{
documentWidget.Content = content;
return documentWidget;
}
return null;
}
I would now like to do something like :
PartialCachingControl documentWidget = (PartialCachingControl)currentPage.LoadControl("/FrontEndShared/Controls/Document/Widget.ascx");
if (documentWidget != null)
{
System.Reflection.PropertyInfo cmsContent = documentWidget.GetType().GetProperty("Content");
documentWidget.Content = content;
return documentWidget;
}
Which fails with "PartialCachingControl doesnt contain a definition for "Content"
or like the solution supposed in Access to PartialCachingControl.CachedControl before Add it but since i cant add the control before setting attributes this doesnt Work.
Any solution
I'm trying to perform an operation on every control on a page that is inherited from a masterpage. I don't know how to access the child pages controls. I have tried recursively getting to my controls like this:
private void checkControls(ControlCollection controlcollection)
{
foreach (Control control in controlcollection)
{
if (control.Controls.Count > 0)
{
Debug.WriteLine(control.GetType().ToString());
checkControls(control.Controls);
}
else
{
Debug.WriteLine(control.GetType().ToString());
}
}
The method is called like this:
protected void resettodefault()
{
checkControls(this.Page.Controls);
}
However, the only controls that are printed from this execution are:
ASP.site_master
System.Web.UI.LiteralControl
I would prefer to access my controls directly (without recursion). Otherwise, how can I modify my recursion to get to the desired page's controls?
I would suggest using a base page instead of a master page, this way your logic for iterating over controls (and whatever you will do with that afterwards) is not tied to which master page a page is using.
As far as getting all the controls on the page, because the controls are hierarchical, as is the HTML they represent, so iterating over them recursively makes sense. However if you are dead set on not recursively getting controls something like this should work:
IEnumerable<Control> GetAllControls()
{
var allControls = new List<Control>();
var currentControls = new Queue<Control>();
currentControls.Enqueue(this.Page);
while (currentControls.Count >0)
{
var c = currentControls.Dequeue();
if (!allControls.Contains(c))
{
allControls.Add(c);
if (c.Controls != null && c.Controls.Count > 0)
{
foreach (Control e in c.Controls)
{
currentControls.Enqueue(e);
}
}
}
}
return allControls;
}
The last thing to consider is the lifecycle of the page, and when you iterate over the controls. If you try to walk to control tree too early not all controls may exist.
EDIT: Updated code.
Update
For validation purposes I would highly recommend using the built in validation controls of asp.net. You can read more about them here. This has the added benefit of providing validation on the client, providing faster UI responses and easing the load off the servers.
For resetting all the textboxes. I would recommend creating a new class for this purpose, then calling upon that class when needed instead of messing with the master page:
public class UIControlsHelper
{
public static void ClearTextboxes(Page page)
{
GetAllControls(page)
.Where(x => typeof(TextBox).IsAssignableFrom(x.GetType())
.ToList()
.ForEach(x => (TextBox)x.Text = string.Empty);
}
IEnumerable<Control> GetAllControls(Page page)
// Same as above, but with the page parameter replaced.
}
}
And in any of your pages:
UIControlsHelper.ClearTextboxes(this);
To access the controls in your child page do the following steps:
1-declare a variable of the type you want to access. For example if you want to access a Label in your child page use:
Label lbl_child=this.ContentPlaceHolder1.findcontrol("your label id in child page") as Label;
Now you have your label and you are free to make changes on it. Every change on this control will be reflected on the child control.
ContentPlaceHolder1 is your contentplace holder id so change it with your content id.
public void ClearTextboxes(Page page) {
GetAllControls(page)
.Where(x => typeof(TextBox).IsAssignableFrom(x.GetType()))
.ToList()
.ForEach(x => ((TextBox)x).Enabled=false);
}
Now I know this does not make for good design practice, however it is legacy code with a bug that needs fixing so I am going to have to live with it.
The scenario is I have a set of nest Master pages (3 deep), call them Base > Template > 2Col. I am working at the 2Col level. As the name suggests the 2Col master page has two content placeholders, MainContent and SideContent.
I have user UserControl in MainContent that needs to reference another UserControl in SideContent.
ContentPlaceHolder ph = (ContentPlaceHolder)this.Page.Master.FindControl("SideContent");
MyUserControl uc = (MyUserControl )ph.FindControl("MyUserControl1");
I am not sure why this doesn't work, the intellisense when I debug would lead me to think that the ContentPlaceHolder is there, but the first line always returns null?
Thanks in advance!
Because of the nesting of Master pages you need access the correct master page like so:
ContentPlaceHolder ph = (ContentPlaceHolder)Parent.Parent.FindControl("SideContent");
Alternatively if you need to find any control on the Page from the Master use the following:
ContentPlaceHolder ph = (ContentPlaceHolder)FindControl(Page.Master, "SideContent");
...
private Control FindControl(Control parent, string id)
{
foreach (Control child in parent.Controls)
{
string childId = string.Empty;
if (child.ID != null)
{
childId = child.ID;
}
if (childId.ToLower() == id.ToLower())
{
return child;
}
else
{
if (child.HasControls())
{
Control response = FindControl(child, id);
if (response != null)
return response;
}
}
}
return null;
}
I want to show some panel with a label, both located on a MasterPage, from inside it's child pages.. I already did the coding on the MasterPage:
public class MyMaster : MasterPage
{
public void ShowPanel(string pMessage)
{
labelInside.Text = pMessage;
myPanel.visible = true;
}
}
Then I make the calls from child pages:
public void ShowPanel(string pMessage)
{
MyMaster masterPage = this.Master as MyMaster;
masterPage.ShowPanel(pMessage);
}
This "works" ok, but it won't show nothing, since I need the page to be "refreshed" in an "ajax-way" like an UpdatePanel, which I can't use because the Trigger is in another page, right?
I really need this to work.. even if you have another completely different way to do this, I would appreciate.
You must place your panel inside an UpdatePanel(UpdateMode conditional) and in ShowPanel call its Update method.
Have you considered having the masterpage just have a placeholder for the label, but having each child page put its own content label inside that placeholder, which it would then have full control over?
you can subClass your page, and expose a property say.. MyPage.FooVisible
than in your masterPage, you can:
myPage = this.Page as MyPage
if (myPage != null) myPage.FooVisble = false;
in your page you can handle that any way you like,
FooVisible {
set { SomeElement.Visible = value; }
}
pseudo code of course :)
I have a master page which is nested 2 levels. It has a master page, and that master page has a master page.
When I stick controls in a ContentPlaceHolder with the name "bcr" - I have to find the controls like so:
Label lblName =(Label)Master.Master.FindControl("bcr").FindControl("bcr").FindControl("Conditional1").FindControl("ctl03").FindControl("lblName");
Am I totally lost? Or is this how it needs to be done?
I am about to work with a MultiView, which is inside of a conditional content control. So if I want to change the view I have to get a reference to that control right? Getting that reference is going to be even nastier! Is there a better way?
Thanks
Finding controls is a pain, and I've been using this method which I got from the CodingHorror blog quite a while ago, with a single modification that returns null if an empty id is passed in.
/// <summary>
/// Recursive FindControl method, to search a control and all child
/// controls for a control with the specified ID.
/// </summary>
/// <returns>Control if found or null</returns>
public static Control FindControlRecursive(Control root, string id)
{
if (id == string.Empty)
return null;
if (root.ID == id)
return root;
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
In your case, I think you'd need the following:
Label lblName = (Label) FindControlRecursive(Page, "lblName");
Using this method is generally much more convenient, as you don't need to know exactly where the control resides to find it (assuming you know the ID, of course), though if you have nested controls with the same name, you'll probably get some strange behavior, so that might be something to watch out for.
Firstly, you should know that MasterPages actually sit inside Pages. So much so that a MasterPage's Load event is actually called after your ASPX's Load event.
This means, the Page object is actually the highest control in the control hierarchy.
So, knowing this, the best way to find any control in such a nested environment, is to write a recursive function that loops through every control and child controls until it finds the one you're looking for. in this case, your MasterPages are actually child controls of the main Page control.
You get to the main Page object from inside any control like this:
C#:
this.Page;
VB.NET
Me.Page
I find that usually, the Control's class FindControl() method is pretty useless, as the enviroment is always nested.
Because if this, I've decided to use .NET's 3.5 new Extension features to extend the Control class.
By using the code below (VB.NET), in say, your AppCode folder, all your controls will now peform a recursive find by calling FindByControlID()
Public Module ControlExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Function FindControlByID(ByRef SourceControl As Control, ByRef ControlID As String) As Control
If Not String.IsNullOrEmpty(ControlID) Then
Return FindControlHelper(Of Control)(SourceControl.Controls, ControlID)
Else
Return Nothing
End If
End Function
Private Function FindControlHelper(Of GenericControlType)(ByVal ConCol As ControlCollection, ByRef ControlID As String) As Control
Dim RetControl As Control
For Each Con As Control In ConCol
If ControlID IsNot Nothing Then
If Con.ID = ControlID Then
Return Con
End If
Else
If TypeOf Con Is GenericControlType Then
Return Con
End If
End If
If Con.HasControls Then
If ControlID IsNot Nothing Then
RetControl = FindControlByID(Con, ControlID)
Else
RetControl = FindControlByType(Of GenericControlType)(Con)
End If
If RetControl IsNot Nothing Then
Return RetControl
End If
End If
Next
Return Nothing
End Function
End Module
Although I love recursion, and agree with andy and Mun, one other approach you may want to consider is to have a strongly typed Master page. All you have to do is add one directive in your aspx page.
Instead of accessing a page's control from your master page, consider accessing a control in your master page from the page itself. This approach makes a lot of sense when you have a header label on your master page, and want to set its value from each page that uses the master.
I'm not 100% sure, but I think this would be simpler technique with nested master pages, as you would just point the VirtualPath to the master containing the control you wish to access. It might prove to be tricky though if you want to access two controls, one in each respective master page.
Here is a code that is more generic and works with a custom condition (that can be a lambda expression!)
Call:
Control founded = parent.FindControl(c => c.ID == "youdId", true);
Control extension
public static class ControlExtensions
{
public static Control FindControl(this Control parent, Func<Control, bool> condition, bool recurse)
{
Control founded = null;
Func<Control, bool> search = null;
search = c => c != parent && condition(c) ? (founded = c) != null :
recurse ? c.Controls.FirstOrDefault(search) != null :
(founded = c.Controls.FirstOrDefault(condition)) != null;
search(parent);
return founded;
}
}
I have used the <%# MasterType VirtualPath="~/MyMaster.master" %> method. I have a property in the main master page then in the detail master page other property with the same name calling the main master property and it works fine.
I have this in the main master page
public string MensajeErrorString
{
set
{
if (value != string.Empty)
{
MensajeError.Visible = true;
MensajeError.InnerHtml = value;
}
else
MensajeError.Visible = false;
}
}
this is just a div element that have to show an error message. I would like to use this same property in the pages with the detail master page(this is nested with the main master).
Then in the detail master I have this
public string MensajeErrorString
{
set
{
Master.MensajeErrorString = value;
}
}
Im calling the main master property from the detail master to create the same behavior.
I just got it working perfectly.
In contentpage.aspx, I wrote the following:
If Master.Master.connectsession.IsConnected Then
my coded comes in here
End If