我正在分配page title
来自code behind
使用C#
。一切正常!但是,事情就是 Title Text is displayed with LINE BREAK
。
那么,如何 prevent the Line Break
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";
}
查看页面来源:
<title>
Sell Your Cell Phone Online or at our Los Angeles locations
</title>
没有换行符的预期渲染:
<title>Sell Your Cell Phone Online or at our Los Angeles locations</title>
注意:
我知道我可以用<title id="mytitle" runat='server'></title>
来完成但我限制使用runat=server
。可能是出于SEO的角度。
请提出其他解决方案吗?
最佳答案
我的团队遇到了同样的问题。我们通过包装原始 HtmlTitle 对象并去除换行符来修复它。
包装类:
/// <summary>
/// Exists to remove the newlines created by asp.net
/// </summary>
public class TrimmedHtmlTitle : HtmlTitle
{
private readonly HtmlTitle _title;
public TrimmedHtmlTitle(HtmlTitle title)
{
_title = title;
}
protected override void Render(HtmlTextWriter output)
{
if (_title == null)
{
return;
}
try
{
using (var stringWriter = new System.IO.StringWriter())
{
using (var htmlTextWriter = new HtmlTextWriter(stringWriter))
{
_title.Text = Text;
_title.RenderControl(htmlTextWriter);
var content = stringWriter.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim();
output.Write(content);
}
}
}
catch { }
}
}
设置和用例:
var head = page.Controls.OfType<HtmlHead>;
if (head != null)
{
var htmlTitle = head.Controls.OfType<HtmlTitle>().FirstOrDefault();
if (htmlTitle != null)
{
var index = head.Controls.IndexOf(htmlTitle);
head.Controls.Remove(htmlTitle);
head.Controls.AddAt(index, new TrimmedHtmlTitle(htmlTitle));
head.Title = "MyTitle";
}
}
关于asp.net - 如何防止asp.net中Title标签换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388559/