ASP.NET 2.0 adds built-in MasterPage support, which is a great convenience for us. However, after using it for a period of time, I found that MasterPage is not so perfect: the nested MasterPage cannot support the design-time interface, and the problem of adding CSS to the Content Page will be mentioned below.
Usually, before 2.0, the syntax for adding a CSS reference to the page was as follows:
<link rel="stylesheet" href="css/test.css" />
It was originally a common practice. But in a sub-page of MasterPage, a very embarrassing situation arises: where should we put the above code?
Because in the specific content page of MasterPage, only the content of each <asp:Content /> tag can be defined. According to the usual practice, we cannot control the <header/> content of the page in aspx. And this <link/> tag must be placed within <header/>. I have tried adding this line of code inside <asp:Content />, but it will prompt an error.
At the same time, we cannot place a ContentPlaceHolder inside the <header/> of MasterPage for future CSS reference code.
So what I did was to define a helper class as follows:
static public class ControlHelper
{
static public void AddStyleSheet(Page page, string cssPath)
{
HtmlLink link = new HtmlLink();
link.Href = cssPath;
link.Attributes["rel"] = "stylesheet";
link.Attributes["type"] = "text/css";
page.Header.Controls.Add(link);
}
}
In this way, on a specific page, we can add CSS references through the following code:
protected void Page_Load(object sender, EventArgs e)
{
ControlHelper.AddStyleSheet(this.Page, "css/projectPage.css");
}
Moreover, this code supports use in specific content pages or a nested Master Page.
At this point, some people may ask, why should CSS be separated and loaded like this? Is it necessary? Wouldn't it be nice if I defined the CSS for all pages into a few common CSS files?
In fact, friends who are familiar with web standard HTML production must know that in a relatively perfect state, the HTML of the page and the CSS used for presentation should be completely separated. For our design based on web standards, we usually first make a positioning code for each frame div in the Master Page, as well as a modification code for the header and footer parts. These are used by every content page and will be placed in a unified CSS. For other specific content pages, each page will have its own different content layout and modification style, so I put the specific parts of each specific page in its own CSS. This forms a CSS model that is merged layer by layer according to the Master Page's implementation level (which can be nested). The advantage is that it realizes the separation of responsibilities of each CSS file, making it easier to understand and maintain.
Since I have not been exposed to ASP.NET 2.0 for a long time, the above is just a little personal experience. If there is a more convenient solution, please give me some advice.
http://rchen.cnblogs.com/archive/2006/05/23/masterpage_with_css.html