How to make Html.DisplayFor display line breaks?

后端 未结 8 1515
梦谈多话
梦谈多话 2020-12-04 21:53

Embarrassingly newbie question:

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

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


        
相关标签:
8条回答
  • 2020-12-04 22:12

    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.

    0 讨论(0)
  • 2020-12-04 22:20

    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)
    
    0 讨论(0)
提交回复
热议问题