tags:

views:

218

answers:

3

I am beginner in .NET. One of my firsts task is to change the meta tags dynamically for dynamically generated pages.

So, I came up with this, but am not too sure on what is considered the "proper" way to do it in .NET.

<head>
<title><%= title %></title>
<meta name="description" content="<%= MetaDescription %>" />
...
</head>

This function lives in my masterpage codebehind and I set a default title, etc on page init (not shown below)

Protected Title As String = ""

Public Sub ChangeTitle(ByVal title As String)
   Title = title
End Sub

I also called this function in any product detail pages to set the appropriate dynamic title.

Is that considered ok in NET? Is this not good or hackish or would you say "if it works, works?


I tried adding runat="server" to the head tag, to use Page.title but then once that got added in, this line <meta name="description" content="<%= MetaDescription %>" /> gets decoded to

<meta name="description" content="&lt;%= MetaDescription %>" />

and my code above then doesn't work to change the meta description.

+4  A: 

If the header is marked Runat="Server" then the Page.Title property of the page will do the change in title automatically for you.

The second one for the meta tag I do the same thing, because it works.

David McEwing
I tried that at first - adding runat="server" to the meta tag, but then once that got added in, this line <meta name="description" content="<%= MetaDescription %>" /> gets decoded.
Dhana
+2  A: 

There is already a property for this: Page.Title

John Rasch
+2  A: 

After adding runat="server" to the head tag so that you can use the Title property, you can use something like this to add meta tags to the head:

public static void AddMeta(string name, string content) {
   Page page = (Page)HttpContext.Current.Handler;
   HtmlMeta meta = new HtmlMeta();
   meta.Name = name;
   meta.Content = content;
   page.Header.Controls.Add(meta);
}
Guffa