ASP.NET MVC Html.En code - 新线 [英] ASP.NET MVC Html.Encode - New lines

查看:135
本文介绍了ASP.NET MVC Html.En code - 新线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Html.En code 似乎只需拨打 HttpUtility.HtmlEn code 替换一些HTML特定的字符与他们的转义序列。

Html.Encode seems to simply call HttpUtility.HtmlEncode to replace a few html specific characters with their escape sequences.

不过,这并没有提供新的线路和多个空格怎么会ptted间$ P $任何代价(标记空白)。所以,我提供了一个用户的文本区域输入信息的明文块,再后来又显示屏幕上的数据(使用 Html.En code ),新线和间隔不会preserved。

However this doesn't provide any consideration for how new lines and multiple spaces will be interpretted (markup whitespace). So I provide a text area for the a user to enter a plain text block of information, and then later display that data on another screen (using Html.Encode), the new lines and spacing will not be preserved.

我认为有2个选择,但也许有更好的第三人可以建议。

I think there are 2 options, but maybe there is a better 3rd someone can suggest.

一个办法是只写一个使用HtmlEn code静态方法,然后替换得到的字符串中的新线,< BR> 和组的多个空格与&放大器; NBSP;

One option would be to just write a static method that uses HtmlEncode, and then replaces new lines in the resulting string with <br> and groups of multiple spaces with &nbsp;

另一种选择是做手脚与空白:在我的样式表pre 属性 - 但是我不知道这是否会产生副作用当效果HTML辅助方法包括新的生产线和Tab键,使网页的源文件pretty。

Another option would be to mess about with the white-space: pre attribute in my style sheets - however I'm not sure if this would produce side effects when Html helper methods include new lines and tabbing to make the page source pretty.

是否有第三个选择,就像一个全局标志,事件或方法重写我可以用它来改变编码的HTML如何做,而不必重做的HTML辅助方法?

Is there a third option, like a global flag, event or method override I can use to change how html encoding is done without having to redo the html helper methods?

推荐答案

HtmlEn code 只是为了恩在HTML显示code字符。它专门针对没有连接code空格字符。

HtmlEncode is only meant to encode characters for display in HTML. It specifically does not encode whitespace characters.

我要和你第一个选项去,使之成为一个的HtmlHelper扩展方法。是这样的:

I would go with your first option, and make it an extension method for HtmlHelper. Something like:

public static string HtmlEncode(this HtmlHelper htmlHelper,
                                string text, 
                                bool preserveWhitespace)
{
    // ...
}

您可以使用与string.replace()为en code中的换行符和空格(或 Regex.Replace 如果你需要更好的匹配)。

You could use String.Replace() to encode the newlines and spaces (or Regex.Replace if you need better matching).

这篇关于ASP.NET MVC Html.En code - 新线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆