Set the master page programmatically in ASP. NET

Source: Internet
Author: User

In many cases, we need to determine which master page to use only when the page is running according to the running status of the project. For example, in the enterprise management system, we require a company department to use a master page, while other departments use another master page. Obviously, the calling method of the previous master page cannot be met at this time. It requires that we must dynamically set the master page in programming mode.
In fact, it is very convenient to dynamically set the master page through programming. You only need to set the Page. MasterPageFile attribute. However, this step must be completed in the Page. Init event phase. After that, setting this attribute will produce an exception. The following code is used:
Protected void Page_PreInit (object sender, EventArgs e)
{
Page. MasterPageFile = "~ /Test. Master ";
}
If you set Page. when The MasterPageFile attribute is set in the Page_Load event, The Page will prompt the error message "The 'masterpagefile' property can only be set in or before the 'page _ PreInit 'event. ". Therefore, you must set the Page. MasterPageFile attribute in the Page. Init event.
When you use programming to dynamically set the master page, you must also pay attention to the following points:
1) Make sure that. the <pages> element of MasterPageFile is not referenced in the @ Page command of the config file or content Page. Only in this way can the Page be successfully loaded and the master Page is introduced.
2) Make sure that the content page does not use the MasterType command to create a strong type reference to the master page.
3) ensure that the content page is fully compatible with the configured master page.

 
Author Ma Wei

Related Article

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.