Shaul Behr
Shaul Behr

Reputation: 38091

How to make Html.DisplayFor display line breaks?

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?

Upvotes: 55

Views: 53023

Answers (9)

Yahoo Serious
Yahoo Serious

Reputation: 3928

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)].

Upvotes: 3

Chtioui Malek
Chtioui Malek

Reputation: 11515

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

Upvotes: 63

Michael Dudgeon
Michael Dudgeon

Reputation: 1

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 />"); }
}

Upvotes: 0

LawMan
LawMan

Reputation: 3625

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);
    }

Upvotes: 1

cwills
cwills

Reputation: 2166

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)

Upvotes: 79

Ian Routledge
Ian Routledge

Reputation: 4042

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)

Upvotes: 4

linkerro
linkerro

Reputation: 5468

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.

Upvotes: 3

slapthelownote
slapthelownote

Reputation: 4279

In your view, you can try something like

@Html.Raw(Html.Encode(Model.MultiLineText).Replace("\n", "<br />"))

Upvotes: 48

Michal B.
Michal B.

Reputation: 5719

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

Upvotes: 2

Related Questions