Render Dynamic MetaTags in ASP.NET Page in Separate Lines

I received a mail today from a DevCurry.com reader after reading my article SEO Enhancements with MetaKeywords and MetaDescription properties in ASP.NET 4.0. Her question was as follows:

In ASP.NET using code with the HTMLMeta class, we can define the HTML meta elements on an ASP.NET page. But the output is all mixed in one line. Can i separate it ?

Let me explain what she means. Here’s a sample code:

HtmlMeta metakeywrd = new HtmlMeta();
metakeywrd.Name = "keywords";
metakeywrd.Content = "add keywords here";

HtmlMeta metadesc = new HtmlMeta();
metadesc.Name = "description";
metadesc.Content = "add meta description here";

Page.Header.Controls.Add(metakeywrd);
Page.Header.Controls.Add(metadesc);

When the page renders, ASP.NET generates meta tags on the same line as shown below.

image

She wanted the meta tags generated on separate lines and I am not sure why!

Anyways the solution is to did this line of code wherever a separate line is needed.

Page.Header.Controls.Add(new LiteralControl("\n"));

Here’s the entire code again

Page.Header.Controls.Add(new LiteralControl("\n"));
HtmlMeta metakeywrd = new HtmlMeta();
metakeywrd.Name = "keywords";
metakeywrd.Content = "add keywords here";

HtmlMeta metadesc = new HtmlMeta();
metadesc.Name = "description";
metadesc.Content = "add meta description here";

Page.Header.Controls.Add(metakeywrd);
Page.Header.Controls.Add(new LiteralControl("\n"));
Page.Header.Controls.Add(metadesc);
Page.Header.Controls.Add(new LiteralControl("\n"));

image

As you can see now, the meta tags are generated on separate lines. If anyone knows a better way or knows the reason why is this really needed, I would love to hear it!






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

5 comments:

TM said...

This was bugging me for some time aswell. I came to the same sort of solution as you but coded differently ;) - Good work!

Nilesh Gule said...

Just a suggestion. Instead of hardcoding the '\n' to insert a new line we could make use of the Environment variable. Environment.Newline.This would make the code work on other platforms where newline is represented using a different control character.

Suprotim Agarwal said...

thomasmutton: Glad it helped!

Nilesh: Good point, but what do you mean by other platforms?

Anonymous said...

Hi, is there a way to edit an existing meta description instead of adding one?


Using Page.Header.Controls.Add creates a duplicate one. Is there any way to just edit the content of the existing one?

Thanks

Milox said...

nice tip!, thanks