在C#中以编程方式添加元标记 [英] Adding meta tag programmatically in C#
问题描述
我正在尝试以编程方式添加<meta>
.当.aspx
页面中的Head
元素带有runat = "server"
时,它可以正常工作.
I'm trying to programmatically add a <meta>
. It is working fine when there is a Head
element with runat = "server"
in the .aspx
page.
后面的代码是:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
this.Page.Header.Controls.Add(meta);
但是我的head标记中有一些脚本,其中包含<% ... %>
之类的代码块,因此我无法保留runat = "server"
的值.
But I have some script in the head tag which contains code blocks like <% ... %>
, so I cannot keep the runat = "server"
value.
问题是我必须以编程方式添加meta标记,因为它取决于数据库中的值.
The problem is I have to add the meta tag programmatically, because it depends on a value from the database.
有没有办法解决这个问题,以便我head元素中的脚本照常工作,并且可以通过编程方式添加meta标签?
Is there a way to solve this issue so that my script inside the head element works as usual and I can add a meta tag programmatically?
推荐答案
OK, I tested the answer by veggerby, and it works perfectly:
在<header>
部分:
<asp:PlaceHolder id="MetaPlaceHolder" runat="server" />
请注意,Visual Studio可能会在PlaceHolder标记上显示警告,因为它没有被识别为标头中的已知元素,但是您可以忽略它.可以.
Note that Visual Studio might show a warning on the PlaceHolder tag, because it is not recognised as a known element inside the header, but you can ignore this. It works.
在C#代码中:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
MetaPlaceHolder.Controls.Add(meta);
或者(因为您已经在标头部分使用<% %>
拥有代码块了),所以您可以直接标记meta并仅从服务器端检索值:
Alternatively (since you already have code blocks using <% %>
in your header section), you can tag the meta directly and retrieve only the value from server side:
<meta name="robots" content="<%=GetMetaRobotsValueFromDatabase()%>" />
这篇关于在C#中以编程方式添加元标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!