How to make Html.DisplayFor display line breaks?

后端 未结 8 1543
梦谈多话
梦谈多话 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:07

    Here's another extension method option.

        public static IHtmlString DisplayFormattedFor(this HtmlHelper htmlHelper, Expression> expression)
        {
            string value = Convert.ToString(ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model);
    
            if (string.IsNullOrWhiteSpace(value))
            {
                return MvcHtmlString.Empty;
            }
    
            value = string.Join("
    ", value.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Select(HttpUtility.HtmlEncode)); return new HtmlString(value); }

提交回复
热议问题