How to make Html.DisplayFor display line breaks?

后端 未结 8 1514
梦谈多话
梦谈多话 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 21:56

    In your view, you can try something like

    @Html.Raw(Html.Encode(Model.MultiLineText).Replace("\n", "<br />"))
    
    0 讨论(0)
  • 2020-12-04 21:59

    i recommend formatting the output with css instead of using cpu consuming server side strings manipulation like .replace,

    just add this style property to render multiline texts :

    .multiline
    {
       white-space: pre-wrap;
    }
    

    then

    <div class="multiline">
      my
      multiline
      text
    </div>
    

    newlines will render like br elements, test it here https://snippet.run/xaf4

    0 讨论(0)
  • 2020-12-04 22:00

    Inspired by DisplayTemplates for common DataTypes, I override (introduce?) a default DisplayTemplate for DataType.MultilineText, /Views/Shared/DisplayTemplates/Multiline.cshtml containing just this line:

    <span style="white-space: pre-wrap">@this.Model</span>
    

    Of course you could also introduce a css-class, or replace newlines inside the view, if you prefer that.
    (I guess this template is automatically resolved, because I had no need for UIHint or any other reference or registration.)

    Using the DisplayTemplate instead of introducing a HtmlHelper-method has the advantage, that it trickles down to properties and views that are not explicitly defined (e.g. DisplayFor(MyClassWithMultilineProperties) will now also correctly display MyClassWithMultilineProperties.MultilineText, if only the property was annotated with [DataType(DataType.MultilineText)].

    0 讨论(0)
  • 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 + "<br />" + b));
            }
        }
    }
    

    And then you'd use it like:

    @using Shaul.Web.Helpers
    
    @Html.ReplaceBreaks(Model.MultiLineText)
    
    0 讨论(0)
  • 2020-12-04 22:07

    Here's another extension method option.

        public static IHtmlString DisplayFormattedFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, string>> expression)
        {
            string value = Convert.ToString(ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model);
    
            if (string.IsNullOrWhiteSpace(value))
            {
                return MvcHtmlString.Empty;
            }
    
            value = string.Join("<br/>", value.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Select(HttpUtility.HtmlEncode));
    
            return new HtmlString(value);
        }
    
    0 讨论(0)
  • 2020-12-04 22:09

    Try using
    @Html.Raw("<p>" + Html.LabelFor(x => x.Name) + "</p>")

    0 讨论(0)
提交回复
热议问题