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?
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()%>" />
Many thanks to Awe for the solution! I have implemented this code in a (error404.ascx) ASP.NET User Control as follows:
<%@ Control Language="C#"%> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { Response.TrySkipIisCustomErrors = true; //Suppress IIS7 custom errors Response.StatusCode = 404; SetRobotsHeaderMetadata(); } private void SetRobotsHeaderMetadata() { HtmlMeta meta = new HtmlMeta(); meta.Name = "robots"; meta.Content = "noindex,follow"; this.Page.Master.FindControl("cphPageMetaData").Controls.Add(meta); } </script>
With the following masterpage:
<%@ Master Language="C#" AutoEventWireup="true" Inherits="MyMaster" %> <script runat="server"> ... </script> <!DOCTYPE html> <html lang="en-GB"> <head> <title>Site title here</title> <asp:contentplaceholder runat="server" id="cphPageMetaData"> </asp:contentplaceholder> </head> <body> ... </body> </html>
Or you could just put your meta-tag in the header, with an ID and a runat="server"... then in the code behind say
myMetaTag.Content = "noindex,follow";
or
myMetaTag.Visible = false;
or whatever you'd like.
I think this is the best approach:
this.Page.Header.Controls.Add(new LiteralControl(@"<meta ... />"));
Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With