Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

asp.net - Adding meta tag programmatically in C#

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.

The code behind is:

HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
this.Page.Header.Controls.Add(meta);

But I have some script in the head tag which contains code blocks like <% ... %>, so I cannot keep the runat = "server" value.

The problem is I have to add the meta tag programmatically, because it depends on a value from the database.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK, I tested the answer by veggerby, and it works perfectly:

In the <header> section:

<asp:PlaceHolder id="MetaPlaceHolder" runat="server" />

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.

In the C# code:

HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
MetaPlaceHolder.Controls.Add(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()%>" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...