Search code examples
asp.net-mvc-3razor

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?


Solution

  • 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)