55

Embarrassingly newbie question:

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

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

does not display the line breaks.

Obviously I could do some fiddling in the model and create another field that replaces \n with <br/>, but that seems kludgy. What's the textbook way to make this work?

Shaul Behr
  • 36,951
  • 69
  • 249
  • 387
  • Does this answer your question? [Replace line break characters with
    in ASP.NET MVC Razor view](https://stackoverflow.com/questions/4220381/replace-line-break-characters-with-br-in-asp-net-mvc-razor-view)
    – avs099 Sep 28 '20 at 15:54

9 Answers9

79

A HtmlHelper extension method to display string values with line breaks:

public static MvcHtmlString DisplayWithBreaksFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
    var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    var model = html.Encode(metadata.Model).Replace("\r\n", "<br />\r\n");

    if (String.IsNullOrEmpty(model))
        return MvcHtmlString.Empty;

    return MvcHtmlString.Create(model);
}

And then you can use the following syntax:

@Html.DisplayWithBreaksFor(m => m.MultiLineField)
cwills
  • 2,136
  • 23
  • 17
  • 1
    Where can I define it in MVC 4 ? – Ofiris Jun 04 '13 at 06:41
  • Good, but instead of returning `MvcHtmlString.Empty` when the value is null or empty I would invoke the standard `HtmlHelper.DisplayFor` method so that any NullDisplayText decoration can be used. – Christopher King Sep 25 '13 at 13:16
  • 5
    For other newbs who might not know, define cwills' DisplayWithBreaksFor() method inside "public static class HtmlExtensions { }" – Steve A Jun 03 '14 at 13:43
  • Using a `DisplayTemplate` instead of introducing a `HtmlHelper`-method has the advantage, that it trickles down to properties and views that are not explicitly defined (see [my answer](https://stackoverflow.com/a/59249806)). – Yahoo Serious Aug 19 '20 at 13:50
62

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://refork.codicode.com/xaf4

Chtioui Malek
  • 11,197
  • 1
  • 72
  • 69
  • 6
    To improve on this so that `Html.DisplayFor` can still be used apply the `[System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.MultilineText)]` attribute to the `MultiLineText` property on the model and create a DisplayTemplate with the contents `@model string @Model` – Mike Sep 26 '13 at 13:27
  • 1
    It probably doesn't matter any more, but this doesn't work on IE9 and below – John May 01 '15 at 19:08
48

In your view, you can try something like

@Html.Raw(Html.Encode(Model.MultiLineText).Replace("\n", "<br />"))
slapthelownote
  • 4,249
  • 1
  • 23
  • 27
  • 4
    should be at least `.Replace("\r\n", ...)`. Also, the [solution from cwills](http://stackoverflow.com/a/10290684/1343917) below is much better, in my opinion. – Dmitry Gonchar Dec 31 '13 at 14:37
  • 1
    No \n is really enough : remaining \r will not harm since they are juste whitespace for html. While matching on \r\n will miss unix style newline and will not handle them. – Frédéric Mar 18 '14 at 14:45
  • Not sure if it was because I'm using `ViewData` instead of a regular property, but in ASP.NET Core Razor, I had to use `@Html.Raw(((string)ViewData["MyText"]).Replace("\n", "
    "))`
    – Neo Jan 24 '19 at 02:50
  • I used a slightly different approach, data stored in my case was SQL text: `@Html.Raw(field.Replace("\n", "
    "))`
    – eoszak Sep 02 '21 at 22:12
4

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)
Ian Routledge
  • 4,012
  • 1
  • 23
  • 28
3

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

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

(Of course you could replace this style, by 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.MyMultilineTextProperty, if the property was annotated with [DataType(DataType.MultilineText)].

Yahoo Serious
  • 3,728
  • 1
  • 33
  • 37
3

You create a display template for your data. Here's a post detailing how to do it. How do I create a MVC Razor template for DisplayFor()

In that template you do the actual translating of newlines into
and whatever other work needs to be done for presentation.

Community
  • 1
  • 1
linkerro
  • 5,318
  • 3
  • 25
  • 29
2

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

Michal B.
  • 5,676
  • 6
  • 42
  • 70
1

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);
    }
LawMan
  • 3,469
  • 1
  • 29
  • 32
0

I had this problem with ASP.NET Core 6. The previous answers here did not work with a linq expression in Html.DisplayFor. Instead I was constantly getting the <br/> tag escaped out in the output HTML. Trying HtmlString helper methods suggestions did not work.

The following solution was discovered through trial and error. The InfoString had CRLF replaced with the <br/> tags as shown in the property code.

Works

@Html.Raw(@Convert.ToString(item.InfoString))

Did not work

@Html.DisplayFor(modelItem => item.InfoString)

FYI - my Info String property:

public string InfoString
{
   get { return MyInfo.Replace(Environment.NewLine,"<br />"); }
}