Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
Shaul Behr Avatar asked Jan 27 '12 08:01

Shaul Behr


3 Answers

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)
like image 188
cwills Avatar answered Nov 11 '22 04:11

cwills


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

like image 60
Chtiwi Malek Avatar answered Nov 11 '22 05:11

Chtiwi Malek


In your view, you can try something like

@Html.Raw(Html.Encode(Model.MultiLineText).Replace("\n", "<br />"))
like image 46
slapthelownote Avatar answered Nov 11 '22 03:11

slapthelownote