Adding meta tag programmatically in C# - 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?

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!

Try moving whatever it is that you are doing in the <% .... %> to the code-behind. If you are using the script to add content into the page, you can replace it with an asp:Literal control and then set the value you were previously calculating in the script block to the code-behind and set Literal.Text to that value.

I haven't tested it, but maybe you can add an <asp:Placeholder> inside the <head></head> tag and add the meta tags to this.

The best solution for this, which I successfully checked without any error or warning:
The JavaScript code, which contains the <% ... %> code, was removed from the head section and placed in the body section.

You could define your meta tag as a static string like so:
Private Shared MetaLanguage As String =
String.Format("<meta http-equiv=""Content-Language"" content=""{0}""/>", CultureInfo.CurrentUICulture.TwoLetterISOLanguageName)
Then place them in your head like so:
<head runat="server">
<%=MetaLanguage%>
</head>
This allow you to use any meta tag values and is easy to read and customize. Note: The use of the Shared keyword (static) helps improve performance.

MetaDescription = "Your meta description goes here";
MetaKeywords = "Keyword1,Keyword2,Keyword3";

OK... I actually only use C#... Or HTML into C#. I never use codebehind, designer or webcontrols in the file aspx... So I program everything from classes... And dynamically.
Result:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
`meta.Content = "Here is what you want";`
var page=HttpContext.Current.Handler as Page;
page.Header.Controls.Add(meta);

Related

How can I make use of a function written in the cs file by calling it in the aspx file

Currently I have the following code in Visual Studio asp.net. It seems like I'm making a new function in the head, while I want to use the one written in the aspx.cs file. The color is not working as I intended, but I'll get back to that.
It could look something like this:
//<script type="text/javascript" src='<%= Active_Frozen(string text, string color) %>'></script>
<head>
<script type="text/javascript">
function Active_Frozen(text,color)
{
document.write(text,color);
}
</script>
</head>
<body>
<script type="text/javascript">
Active_Frozen(text,color);
</script>
</body>
public Tuple<string,string> Active_Frozen(string text, string color) {
connection();
string query = "SELECT CustomerInfo FROM ActiveSubscription WHERE UserName=#UserName";
SqlCommand cmd = new SqlCommand(query, conn);
if(query=="true")
{
text = "Active";
color = "Green";
}
else
{
text = "Frozen";
color= "Red";
}
return Tuple.Create(text, color);
}
EDIT: The reason I have the code in my aspx.cs file is because HTML does not support string hence why it's needs to be amoung the server code. That's why I need to reach the function from the aspx file since I need the text to contain two different options.
Not that way, but you can ofcorse use that specific function in your aspx page, if you bring its implementation here (on aspx page). You can even have all the code in you aspx file. (kind of a single-file page). You Actually want to implement Embedded Code Blocks in ASP.NET Web Pages. Here's an example:
<%# Page Language="C#" %>
<script runat=server>
protected String GetTime()
{
return DateTime.Now.ToString("t");
}
</script>
<html>
<body>
<form id="form1" runat="server">
'Current server time is' <% =GetTime()%>.
</form>
</body>
</html>
But in general, using embedded code blocks for complex programming logic is not a best practice, because when the code is mixed on the page with markup, it can be difficult to debug and maintain. In addition, because the code is executed only during the page's render phase, you have substantially less flexibility than with code-behind or script-block code in scoping your code to the appropriate stage of page processing.
If you want to call code behind function from aspx, the class is public and the function is public static, and as long as you've imported the namespace in an <%# Import %> directive.
user server tag to call server side methods:
<body>
<% Active_Frozen(text,color); %>
</body>

Adding CSS at runtime to an ASP.net master page.

I have an ASP.net web application, and would like to know if is it possible to change the CSS of a site at run time of a master page, and get the CSS file name from a SQL database and add it into the system ?
You can put on the top of the masterpage on aspnet literal and construct the link in the pageload of the masterpage that way you could put a css there
<asp:Literal ID="Css" runat="Server" />
Then on the page load
var cssfilename = GetCssFromDatabase();
Literal.Text = "<link rel=\"stylesheet\" media=\"all\" " + cssfilename + "\" />";
Yes it is. Use <head runat="server"> and you can put anything in there, simplest way probably a Literal control where you append the string from codebehind
Masterpage.master:
<head runat="server">
<title>Your Site</title>
<asp:Literal runat="server" ID="cssLiteral" />
</head>
Masterpage.master.cs:
cssLiteral.Text = "<link rel='stylesheet' type='text/css' href='"+strCssFileName+"' />";
You haven't provided much information of your case, yes it's possible in many ways. Here is a simple example how to change css-file in master-page from a content page:
First add a static variable for example in Global.asax (code in VB.Net)
Public Shared DefaultCssFile As String = "~/MyStyles.css"
In master pages header:
<asp:PlaceHolder runat="server">
<link rel="Stylesheet" type="text/css" href="<%= Page.ResolveUrl(MyApp.Global_asax.DefaultCssFile) %>" />
</asp:PlaceHolder>
Then just change the variables value as you see fit.
MyApp.Global_asax.DefaultCssFile = "~/MyOtherStyles.css"
There are several ways you can achieve this.
Best way I suggest you to use theme and skin file concept.
protected void Page_PreInit(object sender, EventArgs e)
{
switch (Request.QueryString["theme"])
{
case "Blue":
Page.Theme = "BlueTheme";
break;
case "Pink":
Page.Theme = "PinkTheme";
break;
}
}
here you can change the values of your theme run-time from code behind accurately. you can put your .css files into different themes. and as per database conditions you can change values of theme files.
hope this will help.

Is it possible to inject a control into the body of the page from the code behind?

I have a dnn module, and I have a requirement where I need to inject some HTML elements in the body tag of the page.
I tried:
HtmlGenericControl divControl = new HtmlGenericControl("DIV");
divControl.ID = "divControl";
this.Page.Controls.AddAt(0, divControl);
the code above cause the HTML to look like this:
<div id="xxxxxx_divControl"></div><!DOCTYPE html>
<html lang="en-US">
<head id="Head">...
There is no body property on the Page, so is there a way to make the div render in the body tag? (like shown below)
<!DOCTYPE html>
<html lang="en-US">
<head id="Head">...
</head>
<body>
<div id="xxxxxx_divControl"></div>
....
</body>
</html>
You don't want to add it to the Page controls, but to the controls of a container within the page. Use a PlaceHolder for this. Just add the PlaceHolder control to your page where you want to inject content:
<asp:PlaceHolder runat="server" ID="somePlaceHolder" />
Then you would reference that in your code-behind:
HtmlGenericControl divControl = new HtmlGenericControl("DIV");
divControl.ID = "divControl";
this.somePlaceHolder.Controls.AddAt(0, divControl);
You can add runat="server" and an ID to the body tag. Then add your control to the body's control collection. But, depending on your Page Lifecycle, it may not end up where you want it to be, so a Placeholder is still the preferred way.

What's the difference between <head> and <asp:Content ID="HeaderContent" ...>?

This may be a newbie question, but i'm pretty new to asp.net & C# etc.
I'm working with an ASP.net website, and I'm curious about the structure of it (after automatically creating a web project), specifically the following:
I see that in Default.aspx , I have a tag like this:
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>**strong text**
But in Site.master, I have this:
<head runat="server">
*etc*
</head>
So where would I put code if I wanted to include JavaScript code to run, on page load?
I believe you can put your code in any of them. The first one is for adding code or script used by all content pages(that using this master page file) while the second one is if you want to to add script or code from content pages(that should be used only for this specific page)
//in the Master page, the content here is used by all content pages
<head runat="server">
*etc*
</head>
and
//this is specific to the content page that use it. This section needs to be supplied in content pages
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
That section needs to be supplied in each content page and it will be exclusive to that page - no other page can use the script in that section
asp:Content ID="HeaderContent" is a content region. Anything within that tag will get embedded in the associated ContentPlaceHolder in the master page when it is generated.
head is a standard html markup, indicating the page head elements. Typically, the HeadContent placeholder is inside the head tag on the master page.
The head element, container for all the head elements, must use a title for the document. Some other elements it can include: style, base, link, meta, script, noscript.
The asp: Content ID = "HeaderContent" is a content element of the master page.
Have a look at the Plugging in Content part of the following link for detailed information on this: http://odetocode.com/articles/419.aspx
I think you asked when you want to use JavaScript where you put JS in your code.You can put anywhere you wish in asp side between script block such as:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
function Onclick(){
//some codes
}
</script>
</asp:Content>
or
<head runat="server">
<script type="text/javascript">
function Onclick(){
//some codes
}
</script>
</head>
Also you can put JS outside this tag. You only should use tag.

Is it possible to edit the Meta description from code behind?

In the Master Page for Visual Studio 2005 website, I am using meta description as
<meta name="keywords" content="coupons, coupons, online coupons, health deals, health coupons, computer coupons, bargains, hot bargains" />
<meta name="description" content="<%=MyMetaDescription%>" />
I would like to replace the content in each aspx page. How do I use it?
I get the same content as description though I have tried to replace the content in code behind page.
In the code behind, i have called Master.MyMetaDescription = "";
Can someone help me out on this. Thanks a lot in advance!
I would use this :
this.Page.MetaKeywords = "football, sport, golf";
this.Page.MetaDescription = "My site is all about football and golf";
Obviously if you just want to append to them then just use += (don't forget a leading , for the keywords).
Make a content placeholder where the <meta> tag will go in the <head> section:
<html>
<head>
<asp:ContentPlaceHolder ID = "MetaContent" runat = "server" />
</head>
<!-- other content -->
</html>
In your pages then you can replace the content using a different <meta> tag.
<asp:Content ID = "MyMeta" PlaceHolderID = "MetaContent" runat = "server">
<meta />
</asp:Content>
Yuck has already provided a simple enough way to add meta content.
Regardless, see this code project article to see how meta tags can be added from code behind. It also provides a nice solution based on that to easily add meta tags to page.

Categories

Resources