How to make Html.DisplayFor display line breaks?

后端 未结 8 1520
梦谈多话
梦谈多话 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:00

    Inspired by DisplayTemplates for common DataTypes, I override (introduce?) a default DisplayTemplate for DataType.MultilineText, /Views/Shared/DisplayTemplates/Multiline.cshtml containing just this line:

    @this.Model
    

    Of course you could also introduce 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.MultilineText, if only the property was annotated with [DataType(DataType.MultilineText)].

提交回复
热议问题