Realization principle of learning 7--masterpage in web development

Source: Internet
Author: User

MasterPage is a very practical feature introduced by asp.net2.0, how to use it, I don't think I need to say, basically everyone will, here is how it is achieved.

Before delving into the source code to explore MasterPage, I thought the implementation of masterpage should be more complex and wondered why the MasterPage class would inherit from the UserControl class, and it felt like the two were very far apart. Last night, I devoted to spare time, read some of the source code related to MasterPage, finally understand what is going on, in that suddenly understand that moment, really like the enlightened, astounding, have to admire Microsoft's those guys.

Here's the process of my quest (you can skip that part and look directly at the truth behind):

1, I first looked at the Page.processrequestmain method, we know that the page class most of the features, including lifecycle, postback, processpostdata, etc. are implemented in this method, so I think, The realization of masterpage certainly has a lot of embodiment in this method. To my surprise, however, I did not find any clue to the masterpage in the method, but only in this. Performpreinit (), find the only Applymasterpage () method. The method is surprisingly simple and feels like simply setting the recursive levels of masterpage. _masterpageapplied field to True. At the time, I overlooked one important thing, the code for this. Master's access to this property, in fact, the mystery is on the access to this attribute (described below).

private void PerformPreInit()
{
    this.OnPreInit(EventArgs.Empty);
    this.InitializeThemes();
    this.ApplyMasterPage();
    this._preInitWorkComplete = true;
}
 

Page.ApplyMasterPage()
private void ApplyMasterPage()
{
    if (this.Master != null)
    {
        ArrayList appliedMasterFilePaths = new ArrayList();
        appliedMasterFilePaths.Add(this._masterPageFile.VirtualPathString.ToLower(CultureInfo.InvariantCulture));
        MasterPage.ApplyMasterRecursive(this.Master, appliedMasterFilePaths);
    }
}

2, I looked at the source code of MasterPage, surprisingly, unexpectedly so simple, so that I did not find from the source code how much valuable information.

MasterPage

[ControlBuilder (typeof (Masterpagecontrolbuilder)), Designer (" Microsoft.VisualStudio.Web.WebForms.MasterPageWebFormDesigner, Microsoft.VisualStudio.Web, version=8.0.0.0, Culture=neutral, publickeytoken=b03f5f7f11d50a3a ", typeof (IRootDesigner)), ParseChildren (false), AspNetHostingPermission (SecurityAction.LinkDemand, Level=aspnethostingpermissionlevel.minimal), AspNetHostingPermission (SecurityAction.InheritanceDemand, Level=aspnethostingpermissionlevel.minimal)]
public class Masterpage:usercontrol
{
Private IList _contentplaceholders;
Private IDictionary _contenttemplatecollection;
Private IDictionary _contenttemplates;
Private MasterPage _master;
private bool _masterpageapplied;
Private VirtualPath _masterpagefile;
Internal TemplateControl _ownercontrol;

[Editorbrowsable (editorbrowsablestate.advanced)]
protected internal void Addcontenttemplate (string templatename, ITemplate template)
{
if (this._contenttemplatecollection = null)
{
This._contenttemplatecollection = new Hashtable (ten, stringcomparer.ordinalignorecase);
}
Try
{
This._contenttemplatecollection.add (templatename, template);
}
catch (ArgumentException)
{
throw new HttpException (SR. GetString ("Masterpage_multiple_content", new object[] {templatename}));
}
}

internal static void Applymasterrecursive (MasterPage master, IList appliedmasterfilepaths)
{
if (master. Master!= null)
{
String str = Master._masterpagefile.virtualpathstring.tolower (CultureInfo.InvariantCulture);
if (Appliedmasterfilepaths.contains (str))
{
throw new InvalidOperationException (SR. GetString ("masterpage_circular_master_not_allowed", new object[] {master._masterpagefile}));
}
Appliedmasterfilepaths.add (str);
Applymasterrecursive (master. Master, appliedmasterfilepaths);
}
Master._masterpageapplied = true;
}

Internal static MasterPage Createmaster (TemplateControl owner, HttpContext context, VirtualPath MasterPageFile, IDictionary contenttemplatecollection)
{
MasterPage child = null;
if (MasterPageFile = null)
{
if ((contenttemplatecollection!= null) && (Contenttemplatecollection.count > 0))
{
throw new HttpException (SR. GetString ("Content_only_allowed_in_content_page"));
}
return null;
}
VirtualPath virtualpath = virtualpathprovider.combinevirtualpathsinternal (owner. Templatecontrolvirtualpath, MasterPageFile);
Itypedwebobjectfactory Vpathbuildresult = (itypedwebobjectfactory) buildmanager.getvpathbuildresult (context, VirtualPath);
if (!typeof (MasterPage). IsAssignableFrom (Vpathbuildresult.instantiatedtype))
{
throw new HttpException (SR. GetString ("Invalid_master_base", new object[] {masterpagefile}));
}
Child = (MasterPage) vpathbuildresult.createinstance ();
Child. Templatecontrolvirtualpath = virtualpath;
if (owner. Hascontrols ())
{
foreach, control-in owner. Controls)
{
LiteralControl control2 = control as LiteralControl;
if ((control2 = null) | | (Util.firstnonwhitespaceindex (control2). Text) >= 0)
{
throw new HttpException (SR. GetString ("content_allowed_in_top_level_only"));
}
}
Owner. Controls.clear ();
}
if (owner. CONTROLS.ISREADONLY)
{
throw new HttpException (SR. GetString ("masterpage_cannot_applyto_readonly_collection"));
}
if (contenttemplatecollection!= null)
{
foreach (String str in Contenttemplatecollection.keys)
{
if (!child. Contentplaceholders.contains (str. ToLower (CultureInfo.InvariantCulture))
{
throw new HttpException (SR. GetString ("Masterpage_doesnt_have_contentplaceholder", new object[] {str, masterpagefile}));
}
}
Child._contenttemplates = contenttemplatecollection;
}
Child._ownercontrol = owner;
Child. Initializeasusercontrol (owner. Page);
Owner. Controls.Add (child);
return to child;
}

[Browsable (False), editorbrowsable (editorbrowsablestate.advanced)]
protected internal IList ContentPlaceHolders
{
Get
{
if (this._contentplaceholders = null)
{
This._contentplaceholders = new ArrayList ();
}
return this._contentplaceholders;
}
}

[Browsable (False), editorbrowsable (editorbrowsablestate.advanced)]
protected internal IDictionary Contenttemplates
{
Get
{
return this._contenttemplates;
}
}

[Websysdescription ("Masterpage_masterpage"), DesignerSerializationVisibility ( Designerserializationvisibility.hidden), browsable (false)]
Public MasterPage Master
{
Get
{
if ((This._master = null) &&!this._masterpageapplied)
{
This._master = Createmaster (this, this. Context, This._masterpagefile, this._contenttemplatecollection);
}
return this._master;
}
}

[Websysdescription ("Masterpage_masterpagefile"), Webcategory ("Behavior"), DefaultValue ("")]
public string MasterPageFile
{
Get
{
Return virtualpath.getvirtualpathstring (This._masterpagefile);
}
Set
{
if (this._masterpageapplied)
{
throw new InvalidOperationException (SR. GetString ("Propertysetbeforepageevent", new object[] {"MasterPageFile", "Page_PreInit"}));
}
if (Value!= virtualpath.getvirtualpathstring (this._masterpagefile))
{
This._masterpagefile = Virtualpath.createallownull (value);
if (this._master!= null) && this. Controls.contains (This._master))
{
This. Controls.remove (This._master);
}
This._master = null;
}
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.