asp.net - 如何防止asp.net中Title标签换行?

标签 asp.net meta-tags line-breaks page-title

我正在分配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/

相关文章:

javascript 页面导航不起作用

javascript - 通过 javascript 动态更改元标记内容

css - 如何将元标记设置为适合屏幕作为我页面的最小宽度?

html - Chrome 中 br 的边距

html - Plone 中标题换行符的提示

c# - 评论会减慢我网页的执行时间吗?

c# - 临时文件包含对不带参数的构造函数的引用,而它不应该

c# - C#如何在 Crystal 报表的一行中添加一个单词

angular - 元标记未在查看源代码中更新 - Angular

html - 防止在内联 block 元素之前换行