如何基于主页面和内容页面(动态)为项目中的内容页面添加标题和元标记?
我将以下方法用于母版页:
public void SetMetaTags(string title, string description, string keywords)
{
// Get a reference to the HTML Head
HtmlHead headTag = (HtmlHead)Page.Header;
// Set the page title
headTag.Title = title;
// Add a Description meta tag
HtmlMeta metaTag = new HtmlMeta();
metaTag.Name = "Description";
metaTag.Content = description;
headTag.Controls.Add(metaTag);
// Add a Keywords meta tag
metaTag = new HtmlMeta();
metaTag.Name = "Keywords";
metaTag.Content = keywords;
headTag.Controls.Add(metaTag);
}
所以我不知道为什么内容页面的Page_Load
中的以下代码有错误:
protected void Page_Load(object sender, EventArgs e)
{
MasterPage MyMasterPage = (MasterPage)Master;
// Error on this line:
MyMasterPage.SetMetaTags("Title", "description", "keywords");
}
,错误是:
Error 17 'System.Web.UI.MasterPage' does not contain a definition for
'SetMetaTags' and no extension method 'SetMetaTags' accepting a first argument of
type 'System.Web.UI.MasterPage' could be found (are you missing a using directive
or an assembly reference?)
C:\Javad\---\AlmasAfzar\AlmasAfzar\AlmasAfzar\Products.aspx.cs 16 26
AlmasAfzar
感谢未来的进展
最好的问候
答案 0 :(得分:1)
您需要将从Page.Master返回的类型转换为主页的类型,而不是System.Web.UI.MasterPage。
因此,如果使用SetMetaTags方法的主页面类名为MasterWithMetaTags,则您的Page_Load代码需要如下所示:
protected void Page_Load(object sender, EventArgs e)
{
MasterWithMetaTags MyMasterPage = (MasterWithMetaTags)Master;
MyMasterPage.SetMetaTags("Title", "description", "keywords");
}
答案 1 :(得分:0)
没有提到错误是什么,我只能按照你所说的去做。我会确保你的aspx文件中有这个指令:
<%@ MasterType VirtualPath="PathToYourMasterFile" %>
答案 2 :(得分:0)
您可以使用Page.Header.Title作为页面标题。 这是我的。
#region meta tags and title
Page.Header.Title = dtArticleDetails.Rows[0]["title"].ToString();
string Keywords = dtArticleDetails.Rows[0]["keywords"].ToString();
string Description = dtArticleDetails.Rows[0]["description"].ToString();
HtmlMeta keywordss = new HtmlMeta();
HtmlHead head = (HtmlHead)Page.Header;
keywordss.Name = "keywords";
keywordss.Content = Keywords;
head.Controls.Add(keywordss);
HtmlMeta desc = new HtmlMeta();
desc.Name = "description";
desc.Content = Description;
HtmlHead head2 = (HtmlHead)Page.Header;
head2.Controls.Add(desc);
#endregion