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?
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)
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
In your view, you can try something like
@Html.Raw(Html.Encode(Model.MultiLineText).Replace("\n", "<br />"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With