开发者

C# & Adding Dynamic META Tags

开发者 https://www.devze.com 2022-12-29 04:40 出处:网络
I have this code protected void Page_Load(object sender, EventArgs e) { DataSet.DestinationsDataTable GetDestinations = (DataSet.DestinationsDataTable)dta.GetData();

I have this code

 protected void Page_Load(object sender, EventArgs e)
{
    DataSet.DestinationsDataTable GetDestinations = (DataSet.DestinationsDataTable)dta.GetData();
    Page.Title = GetDestinations.Rows[0]["Meta_Title"].ToString();

    HtmlMeta hm = new HtmlMeta();
    HtmlHead head = (HtmlHead)Page.Header开发者_运维问答;
    hm.Name = GetDestinations.Rows[0]["Meta_Desc"].ToString();
    hm.Content = GetDestinations.Rows[0]["Meta_Key"].ToString();
    head.Controls.Add(hm);  
}

And it's returning this error (on a content page)

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Thoughts?


I don't see what's not clear from the error message. Your <head> tag contains a <% %> block, and therefore you cannot dynamically add controls there at runtime.

To resolve this, add a placeholder and put your meta tags there:

<html>
    <head>
        ...
        <asp:PlaceHolder runat="server" ID="metaTags" />
    </head>
...

And then:

protected void Page_Load(object sender, EventArgs e)
{
    DataSet.DestinationsDataTable GetDestinations = (DataSet.DestinationsDataTable)dta.GetData();
    Page.Title = GetDestinations.Rows[0]["Meta_Title"].ToString();

    HtmlMeta hm = new HtmlMeta();
    hm.Name = GetDestinations.Rows[0]["Meta_Desc"].ToString();
    hm.Content = GetDestinations.Rows[0]["Meta_Key"].ToString();
    this.metaTags.Controls.Add(hm);  
}
0

精彩评论

暂无评论...
验证码 换一张
取 消