Reputation: 765
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
Upvotes: 4
Views: 11704
Reputation: 11515
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
Upvotes: 6
Reputation: 3908
As mentioned in make DisplayFor display line breaks, I override (introduce?) a default DisplayTemplate for DataType.MultilineText
, /Views/Shared/DisplayTemplates/MultilineText.cshtml
containing just this line:
<span style="white-space: pre-wrap">@this.Model</span>
I guess this template is automatically resolved, because I had no need for UIHint
or any other reference or registration.
(Of course you could also introduce a css-class, or replace newlines inside the view, if you prefer that.)
Using the default DisplayTemplate will fix the line breaks for all properties annotated with the (type-safe, meaningful) [DataType(DataType.MultilineText)]
, instead of just the ones annotated with UIHint("DisplayPostalAddr")
.
Upvotes: 1
Reputation: 857
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; }
Upvotes: 6