Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a @Html.DisplayFor multiline in MVC 4

I am trying to display a customer address in multiline which works for @Html.EditorFor but not @Html.DisplayFor. I have tried other posts on here but have not got it to work. Here is what have started with and what I have tried with no luck

@Html.DisplayFor(model => model.CustomerPostalAddress)
@Html.Raw(Html.Encode(Model.CustomerPostalAddress).Replace("\n","<br/>"))

Here is the field in the model

 [DataType(DataType.MultilineText)]
 public string CustomerPostalAddress { get; set; }

Any help would be much appreciated

like image 903
WillNZ Avatar asked Dec 12 '22 20:12

WillNZ


2 Answers

You would want to create a DisplayTemplate in Views/Shared/DisplayTemplates/DisplayPostalAddr.cshtml

@model string

<p>@Model</p>

then give you model a hint on how to display it

[DataType(DataType.MultilineText)]
[UIHint("DisplayPostalAddr")]
public string CustomerPostalAddress { get; set; }
like image 153
kevin_fitz Avatar answered Jan 08 '23 16:01

kevin_fitz


just add this css style property to render multiline texts, this is better then cpu consuming server side strings manipulation like .replace :

.multiline
{
   white-space: pre-wrap;
}

then

<div class="multiline">
  my multiline
  text
</div>

this will render newlines like br elements.

try it here : https://refork.codicode.com/xaf4

like image 40
Chtiwi Malek Avatar answered Jan 08 '23 17:01

Chtiwi Malek