asp.net mvc的转换\\ n新行到html符 [英] asp.net mvc convert \n new line to html breaks

查看:103
本文介绍了asp.net mvc的转换\\ n新行到html符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的textarea MVC中。当输入到数据,我展示它返回给用户,我怎么显示换行?

我显示是这样的:

 <%= Model.Description%GT;


解决方案

下面的类实现了的HtmlHelper,适当带codeS的文本:

 公共静态类HtmlExtensions
{
    公共静态MvcHtmlString Nl2Br(此的HtmlHelper的HtmlHelper,字符串文本)
    {
        如果(string.IsNullOrEmpty(文本))
            返回MvcHtmlString.Create(文本);
        其他
        {
            StringBuilder的建设者=新的StringBuilder();
            字符串[] =行text.Split('\\ n');
            的for(int i = 0; I< lines.Length;我++)
            {
                如果(I 0)
                    builder.Append(< BR /> \\ n);
                builder.Append(HttpUtility.HtmlEn code(行[I]));
            }
            返回MvcHtmlString.Create(builder.ToString());
        }
    }
}

这很容易在你的意见是:

 <%= Html.Nl2Br(Model.MultilineText)%GT;

或用剃刀:

  @ Html.Nl2Br(Model.MultilineText)

I have a textarea in mvc. When data is entered into that and I'm displaying it back to the user, how do I show the line breaks?

I display like this:

<%= Model.Description%>

解决方案

The following class implements a HtmlHelper that properly encodes the text:

public static class HtmlExtensions
{
    public static MvcHtmlString Nl2Br(this HtmlHelper htmlHelper, string text)
    {
        if (string.IsNullOrEmpty(text))
            return MvcHtmlString.Create(text);
        else
        {
            StringBuilder builder = new StringBuilder();
            string[] lines = text.Split('\n');
            for (int i = 0; i < lines.Length; i++)
            {
                if (i > 0)
                    builder.Append("<br/>\n");
                builder.Append(HttpUtility.HtmlEncode(lines[i]));
            }
            return MvcHtmlString.Create(builder.ToString());
        }
    }
}

It's easy to use in your views:

<%= Html.Nl2Br(Model.MultilineText) %>

Or with Razor:

@Html.Nl2Br(Model.MultilineText)

这篇关于asp.net mvc的转换\\ n新行到html符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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