Add multiple elements to a HtmlHead object from within a class
I have a website with a bunch of pages. I have 4 master pages that all of the pages use. Each page uses different css and JavaScript in开发者_JS百科cludes inside of the head tags. I would like to add the title, meta description, and meta keywords tags in through a call to a class that will reference a database table. However, I cannot figure out a way to pass the page or an HthmlHead object into the class without it throwing an error. I have tried doing
HtmlHead head = Page.Header;
Page.Controls.Remove(Page.FindControl("HeadElement"));
Page.FindControl("HtmlElement").Controls.AddAt(0,HeaderText.getHeaderText(head, Request.Url.AbsolutePath));
and
Page = p2
Page = HeaderText.getHeaderText(p2, Request.Url.AbsolutePath));
In both cases I changed my class HeaderText.getHeaderText to return the page or HtmlHead types depending on what I was doing. I setup the class to look like this:
public class HeaderText
{
private HeaderText() { }
public static HtmlHead getHeaderText(HtmlHead head, String URL)
Is there a better or easier way to do this?
You could try one of these two suggestions:
1) Make your Master Pages all have a HeadContentPlaceHolder which exists inside of a tag that does not have a runat="server" attribute. Then you can manipulate those contents at your leisure.
<head>
<link ....>
<script....>
<meta......>
<asp:ContentPlaceHolder runat="server" ID="headContentPlaceHolder"></asp:ContentPlaceHolder>
</head>
You could also use the Page.Title to set the title easily from each Page
2) use the MasterType reference on each Content Pages
<%@ MasterType TypeName="My.App.MasterPage" %>
So if you had a "SetHeaderElements" method in your Master page class, you could call them from each Content Page that had that MasterType defined
Page.Master.SetHeaderElements(meta, css, js);
You can also try to avoid having this code in each of your Content Pages by have a PageBase class which returns your Master Page like this
public class PageBase : Page
{
public IMasterPage MasterPage { get { return Page.Master as IMasterPage; }}
}
Then create an IMasterPage interface with the SetHeaderElements() method and have each of your MasterPage classes implement this interface.
精彩评论