How to make Html.DisplayFor display line breaks?

后端 未结 8 1539
梦谈多话
梦谈多话 2020-12-04 21:53

Embarrassingly newbie question:

I have a string field in my model that contains line breaks.

@Html.DisplayFor(x => x.MultiLineText)         


        
8条回答
  •  悲&欢浪女
    2020-12-04 22:04

    The display template is probably the best solution but there is another easy option of using an html helper if you know you're just displaying a string, e.g.:

    namespace Shaul.Web.Helpers
    {
        public static class HtmlHelpers
        {
            public static IHtmlString ReplaceBreaks(this HtmlHelper helper, string str)
            {
                return MvcHtmlString.Create(str.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).Aggregate((a, b) => a + "
    " + b)); } } }

    And then you'd use it like:

    @using Shaul.Web.Helpers
    
    @Html.ReplaceBreaks(Model.MultiLineText)
    

提交回复
热议问题