Html.Encode
似乎只是简单地调用HttpUtility.HtmlEncode
将一些html特定字符替换为其转义序列。
然而,这并未考虑如何解释新行和多个空格(标记空白)。因此,我为用户提供了一个文本区域,用于输入纯文本信息块,然后在另一个屏幕上显示该数据(使用Html.Encode
),新行和间距将不会被保留。
我认为有2种选择,但也许有人会提出更好的建议。
一种选择是只编写一个使用HtmlEncode的静态方法,然后用<br>
替换结果字符串中的新行和
另一种选择是在我的样式表中弄乱white-space: pre
属性 - 但是我不确定当Html帮助方法包含新行和Tab键以使页面源非常漂亮时是否会产生副作用
是否有第三个选项,如全局标志,事件或方法覆盖,我可以用来改变html编码的方式,而不必重做html帮助器方法?
答案 0 :(得分:23)
HtmlEncode
仅用于编码以HTML格式显示的字符。它特别不编码空格字符。
我会选择第一个选项,并将其作为HtmlHelper的扩展方法。类似的东西:
public static string HtmlEncode(this HtmlHelper htmlHelper,
string text,
bool preserveWhitespace)
{
// ...
}
如果您需要更好的匹配,可以使用String.Replace()
对换行符和空格进行编码(或Regex.Replace
。)
答案 1 :(得分:8)
使用style="white-space:pre-wrap;"
为我工作。每this article。
答案 2 :(得分:5)
如果你使用Razor,你可以这样做:
@MvcHtmlString.Create(Html.Encode(strToEncode).Replace(Environment.NewLine, "<br />"))
在您的视图中,或在您的控制器中:
HttpServerUtility httpUtil = new HttpServerUtility();
MvcHtmlString encoded = httpUtil.HtmlEncode(strToEncode).Replace(Environment.NewLine, "<br />");
我没有测试过控制器方法,但它应该以相同的方式工作。
答案 3 :(得分:3)
将您的输出放在<pre></pre>
和/或<code></code>
块中。 E.g:
<pre>@someValue</pre> / <code>@someValue</code>
在现有div
上使用等效的css:
<div style="white-space:pre-wrap;">@someValue</div>
取决于您是否需要语义标记或是否要使用css。我认为这些都比插入<br/>
标签更整洁。
答案 4 :(得分:0)
/// <summary>
/// Returns html string with new lines as br tags
/// </summary>
public static MvcHtmlString ConvertNewLinesToBr<TModel>(this HtmlHelper<TModel> html, string text)
{
return new MvcHtmlString(html.Encode(text).Replace(Environment.NewLine, "<br />"));
}