Altaf Khatri
Altaf Khatri

RSS feed for website. Twitter account of website.
∗Recently Added - How to take care of Betta fighter fish and increase life span?  10/30/2013

Find me on web




How to remove unncessary spaces and line breaks in title when using contentplaceholder in ASP.NET MVC?

After installing MVC and setting up MVC with ASP.NET in Visual Studio, creating any new MVC ASP.NET Web Application will render the webpages using the derived classes within MVC handlers. ASP.Net MVC classes renders HTML page.

When the title element in the head section of master page is populated with the contentplaceholder in the child pages, a line break and spaces appears in the rendered HTML page (right click on the webpage and view source. Check the title element.). If you are picky about this and are really Search Engine Optimization(SEO) concious then you will want to avoid this.

Trying different strategies didn't work for me.

  1. I tried aligning the contentplaceholder in the master page and adjusting the content in the child pages. Didn't work.
  2. Tried using Trim() function by putting the entire content of the child page as string. Didn't work.
  3. Removed the contentplaceholder and tried putting hard coded string in the title. Didn't work

Finally, I used the following approach and it did the trick:

  1. Make the head section of the default MVC page as invisible. Normally when you create a view page, a default head section is part of the webpage. This is with runat attribute.
    <head runat="server" visible="false"/>
  2. Introduce the new head section without the runat="server" tag.

This should resolve the problem. Now for the inquisitives, why this behavior?

Observe that the ASP.NET MVC default head is with runat="server". ASP.NET MVC dll renders this header. While rendering it parses the title element and updates the content in it.

While parsing, the html title element gets rendered with line breaks and spaces. It is the default behavior of MVC. I hope MVC team will take care of this issue in future releases. ASP.NET MVC is meant to be SEO friendly and rendering the title with line breaks may not be liked by search engines.

SiteMap  |  Contact Me