Solved

Access base class property from user control

Posted on 2004-08-03
8
598 Views
Last Modified: 2008-02-01
I use a base class as a templating solution for my ASP.NET apps. I then inherit all ASPX pages formthis class to apply the template.
In this base class I create a number of public properties which allows me to access elements of the template from each specific page. So for example I have a PlaceHolder called "ExampleControl". Rough code below but you should know what I mean:
public class TemplatedPage : System.Web.UI.Page
{
      this.ExampleContent.ID = "ExampleContent";

}

public System.Web.UI.WebControls.PlaceHolder ExampleContent
{
  get
  { return template_content.Content; }
  set
  { this.template_content.Content = value; }
}

Then in the individual ASPX page which inherits from this class, I can go Page.ExampleControl and add elements dynamically, e.g.
public class Examplepage : TemplatedPage
{
      private void Page_Load(object sender, System.EventArgs e)
      {
            base.ExampleContent.Controls.Add(new LiteralControl("Hello"));

      }
}

The problem I currently have is that I have recently changed my app for UrlRewriting so that there is only a single ASPX page which then loads child ASCX controls for content. However I still need to be able to access the properties of the base class from the user controls and I dont seem to be able to. Any ideas how I can achieve this?

I have tried various combinations of the following:
PlaceHolder ph_Content = new PlaceHolder();
ph_Content = (PlaceHolder) base.Page.FindControl("ExampleContent");
ph_Content.Controls.Add(new LiteralControl("Hooray!"));

Thanks



0
Comment
Question by:jonnyboy69
  • 4
  • 4
8 Comments
 
LVL 35

Expert Comment

by:YZlat
ID: 11704897
Project1.BaseClassName.Property
0
 

Author Comment

by:jonnyboy69
ID: 11705964
Cool that works thanks. I'll up to 200 points if you can help me once more.

Ive since added a new property to the class to set the page title. However its not working when I set it from the ASPX page?

So in the ASPX page inherited from the template class I go: this.PageTitle = "Some page title"; which should set the page title, but it doesnt for dsome reason.

Here is the template class:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Collections;
using Mulberrybush;
using Mulberrybush.Architecture;
using CYBERAKT;

namespace Mulberrybush.Templates
{
      /// <summary>
      ///            Generic Page Templatizer.
      
      /// </summary>
      ///
  public class TemplatedPage : System.Web.UI.Page
  {
        public Mulberrybush.Templates.ITemplate_PageContent template_content;
        protected DerivedTool.WebControls.CHtmlForm MainForm = new DerivedTool.WebControls.CHtmlForm();

        private string templatePath_content = "";
        private char[] sep = new char[]{Convert.ToChar(";")};
        private string _PageTitle;
   
        // Constructor
        public TemplatedPage()
        {}

        // Loads template using IPageTemplate interface
        // 1 : Gets CurrentSite alias from Globals.CurrentSite property
        // 2 : Determines which template file we need to load for this particular site(CurrentSite)
        // 3 : Loads template control and adds to page
        // 4 : Get PageSettings object from HTTPContext
        // 5 : Load settings for this page from PageSettings object into template control
        #region protected void LoadTemplate()
        protected void LoadTemplate()
        {

              // Obtain PageSettings object from Current Context (Set in global.asax)
              PageSettings pageSettings = (PageSettings) HttpContext.Current.Items["PageSettings"];
            
              // Get path of content template file we need to load for this page
              if(templatePath_content == String.Empty)
                    // Set to single page template for now
                    templatePath_content = "/_controls/templates/pagecontent.ascx";

              // Initialise template controls
              template_content = (ITemplate_PageContent)Page.LoadControl(templatePath_content);

              // Add Content controls
              string contentControls = pageSettings.ContentModules;
              if (contentControls != null)
              {
                    foreach (string contentControl in contentControls.Split(sep))                  
                          template_content.Content.Controls.Add((System.Web.UI.Control)this.LoadControl(this.Request.ApplicationPath + contentControl));
              }
             
              // Add RightBar controls
              string rightbarControls = pageSettings.RightBarModules;
              if (rightbarControls != null)
              {
                    foreach (string rbcontrol in rightbarControls.Split(sep))                  
                          template_content.RightBar.Controls.Add((System.Web.UI.Control)this.LoadControl(this.Request.ApplicationPath + rbcontrol));
              }

              // Add Absolutely positioned controls
              string absoluteControls = pageSettings.AbsoluteModules;
              if (absoluteControls != null)
              {
                    foreach (string abcontrol in absoluteControls.Split(sep))                  
                          template_content.AbsoluteContent.Controls.Add((System.Web.UI.Control)this.LoadControl(this.Request.ApplicationPath + abcontrol));
              }

              // Add ID's to template controls
              this.Content.ID = "Content";
              this.RightBar.ID = "RightBar";
              this.AbsoluteContent.ID = "AbsoluteContent";

              // Add content template to HTML form
              MainForm.Action = Globals.PathandQuery;
              MainForm.ID = "MainForm";
              MainForm.Controls.Add((System.Web.UI.Control)template_content);

              // Build the page using these controls we have created + wrappers of pagetop & pagebot
              this.BuildPage(this.BuildPageTop(pageSettings), this.BuildPageBot(), this.MainForm);
             
        }
        #endregion

        // Adds the various controls created to the page
        #region private void BuildPage
        private void BuildPage(string PageTop, string PageBot, System.Web.UI.Control MainForm)
        {
              // Add PageTop control to page
              base.Controls.Add(new LiteralControl(PageTop));

              // Add Content control to page
              base.Controls.Add((System.Web.UI.Control)MainForm);

              // Add PageBot control to page
              base.Controls.Add(new LiteralControl(PageBot));

        }
        #endregion

        // Builds string of all HTML required to build page up until we load HTML form
        // 1 : PageSettings object to add local properties
        #region private string BuildPageTop()
        private string BuildPageTop(PageSettings pageSettings)
        {
              StringBuilder sb_PageTop = new StringBuilder();

              // DTD statement
              // Strict
              sb_PageTop.Append("<?xml version='1.0' encoding='utf-8'?>");
              sb_PageTop.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\" >");
              sb_PageTop.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\" >");
              // Transitional
              //sb_PageTop.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\" ><html>");

              // Start head tag
              sb_PageTop.Append("<head>\n");
              // Page title
              //_PageTitle = pageSettings.Title;
              sb_PageTop.Append("<title>" + _PageTitle + "</title>\n");
               // Meta tags
              sb_PageTop.Append(pageSettings.Metas);

            // JavaScript files
              // 1. Scripts from pagettemplate settings (pageSettings.Scripts)
              sb_PageTop.Append(pageSettings.Scripts);

            // CSS files
              // 1a. Global style sheet for all sites
              sb_PageTop.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"/_styles/global.css\" media=\"all\" />");
              // 1b. PRINT VERSION of Global style sheet
              sb_PageTop.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"/_styles/global_print.css\" media=\"print\" />");
               
              // 2. Style sheets from pageSettings object
              // # Passes string of multiple stylesheet href's. Need to split and then build full style sheet reference
              string s_StyleSheets = pageSettings.Styles;
              if (s_StyleSheets != null)
              {
                    foreach (string styleSheet in s_StyleSheets.Split(sep))        
                    {          
                          sb_PageTop.Append("<link rel=\"StyleSheet\" type=\"text/css\" media=\"all\" href=\"" + styleSheet + "\" />");  
                    }
              }

              // Close Head tag & open body section + append and BodyOnload statements
              sb_PageTop.Append("</head>\n");

              // Body tag
              sb_PageTop.Append("<body");
              // Add class attribute to determine which background image to display
              sb_PageTop.Append(" class=\"" + pageSettings.AreaSpecificPrefix + "\"");
              // Add any JS OnLoad calls
              if(pageSettings.BodyOnLoad != null)
                   sb_PageTop.Append(" onLoad=\"" + pageSettings.BodyOnLoad + "\"");
              // Close tag
              sb_PageTop.Append(">\n");

              // Return string of HTML
              return (string) sb_PageTop.ToString();
             
        }
        #endregion

        // Builds string of HTML required to wrap content in and close all necessary tags
        #region private string BuildPageBot()
        private string BuildPageBot()
        {
               string s_PageBot = "</body></html>";
               return (string) s_PageBot;

        }
        #endregion
        
        // Make sure all controls are loaded and parsed correctly
        #region protected override void AddParsedSubObject(System.Object Control)
        protected override void AddParsedSubObject(System.Object Control)
        {
              // Make sure template is instantiated
              if(template_content == null)
              { LoadTemplate(); }

              // Make sure child controls are parsed correctly
              if(template_content.Content != null)
                    template_content.Content.Controls.Add((System.Web.UI.Control)Control);
              else
                    Page.Controls.Add((System.Web.UI.Control)Control);
        }
        #endregion
   
        // Public controls to expose in page
        // i.e. Page.LeftBar.Controls.Add();
        #region System.Web.UI.WebControls.PlaceHolder Content
        public System.Web.UI.WebControls.PlaceHolder Content
        {
              get
              { return template_content.Content; }
              set
              {
                    this.template_content.Content = value;
              }
        }
        #endregion

        #region System.Web.UI.WebControls.PlaceHolder RightBar
        public System.Web.UI.WebControls.PlaceHolder RightBar
        {
              get
              { return template_content.RightBar; }
        }
        #endregion

        #region System.Web.UI.WebControls.PlaceHolder AbsoluteContent
        public System.Web.UI.WebControls.PlaceHolder AbsoluteContent
        {
              get
              { return template_content.AbsoluteContent; }
        }
        #endregion

        #region public string PageTitle
        public string PageTitle
        {
              get
              { return this._PageTitle; }
              set
              { this._PageTitle = value; }
        }
        #endregion


        #region override protected void OnInit(System.EventArgs Arguments)
        override protected void OnInit(System.EventArgs Arguments)
        {
              // Check template is loaded
              if(template_content == null)
              { LoadTemplate(); }
             
              base.OnInit(Arguments);
        }
        #endregion

  }
}
0
 
LVL 35

Expert Comment

by:YZlat
ID: 11707538
0
 

Author Comment

by:jonnyboy69
ID: 11708148
Sorry I need to know why the above code is not working as opposed to finding a different solution. If no response within a day I'll award points here and post separately.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 35

Expert Comment

by:YZlat
ID: 11709231
this.PageTitle = "Some page title";  is not going to work.
Add id and runat=server to your title tag
0
 
LVL 35

Accepted Solution

by:
YZlat earned 200 total points
ID: 11709252
you have no choice, you'll ahve to use System.Web.UI.HtmlControls.HtmlGenericControl
0
 

Author Comment

by:jonnyboy69
ID: 11709913
But there is no title tag to set server side as I create it programmatically in the base template code. Its not created in the template user control (as I need to wrap all this in a form tag) like the other publically exposed elements

e.g
//_PageTitle = pageSettings.Title;
sb_PageTop.Append("<title>" + _PageTitle + "</title>\n");

I did originally think I could create a new "pagetop" user control template which exposes server side controls for these additional elements (title and meta tags) I need. I just didnt think this way the best / quickest way and just assumed it would be easy to expose a public property in the class itself. ?? I still dont get why I cant create a public property for the class and set it in the page though?

Thanks for your help
0
 

Author Comment

by:jonnyboy69
ID: 11713308
Got it working programmatically so here's the points
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
This video discusses moving either the default database or any database to a new volume.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now