I am assigning the page title
from code behind
using C#
. All works fine! But, just the thing is the Title Text is displayed with LINE BREAK
.
So, how to prevent the Line Break
of the Title
?
phonesOnly.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage_New.master" AutoEventWireup="true" CodeFile="phonesOnly.aspx.cs" Inherits="phonesOnly" %>
phonesOnly.aspx.cs
protected void SetTitle()
{
this.Page.Title = "Sell Your Cell Phone Online or at our Los Angeles locations";
}
View Source of Page:
<title>
Sell Your Cell Phone Online or at our Los Angeles locations
</title>
Expected Rendering without Line Break:
<title>Sell Your Cell Phone Online or at our Los Angeles locations</title>
NOTE:
I know I can be done with <title id="mytitle" runat='server'></title>
but I am Restricted to use runat=server
. May be due to SEO perspective.
Please suggest any other solution?
2
Answers
Unfortunately, as soon as you add a runat=”server” to the
<head>
tag, this is what happens. TheHtmlHead
class parses your content inside the head tag, then rewrites it, and it unfortunately messes it up when it does so. The only way to get properly formatted output is to avoid using a server side head tag, which means you cannot use the Page.Title property, so you have to use your own title variable, but you can remove the id by assigning null to the id in the code behind.The following works as expected:
Then in code behind:
This generates the following HTML.
This has the advantage that it doesn’t bunch up all your meta tags on one line either.
If you’re using a Master page, then you’ll have to do a little hoop jumping to get the control from the master page instead. Either create a property on the Master page to return the control, or use FindControl like this:
Make sure you have not set the ID to null in the master page, or the FindControl won’t work in the content page.
My team ran into the same issue. We fixed it by wrapping the original HtmlTitle object and stripping the line breaks.
Wrapper class:
Setup and use case: