1

Let me preface this by saying that I know that I can use HTML.Raw() to display HTML contained in a string. However, I believe that the purpose of MVC is to separate the code logic and to allow front end developers to focus on UI and not logic. Therefore, I try to pass everything I can from the model exactly as I want it to look.

That brings me to my question. I have a model that contains an address. I have written a function that returns the address in a few different versions (single line, two line, multiline) and I'm setting these as HtmlString objects.

public HtmlString TwoLine { get { return ReturnFullAddress(2); } }
/* function removed for brevity */

However, when I write the following razor code:

@Html.DisplayFor(modelItem => item.Address.TwoLine)

No text is returned within the view. When I debug this, there IS a value properly assigned within Address.TwoLine, but it is within { } (which I thought was strange).

How do I make this work, or why doesn't this work?

tereško
  • 58,060
  • 25
  • 98
  • 150
Eric K
  • 689
  • 9
  • 26

1 Answers1

2

DisplayFor() doesn't know how to handle HtmlString properties.
You should just print the value directly: @Model.Address.TwoLine

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • `DisplayFor()` does not accept `HtmlString`. Changing my variable back to a string and using `DisplayFor()` results in nothing appearing. Using `Html.Raw` works still. Also, just a note... this is within a foreach loop. – Eric K Dec 05 '12 at 21:43
  • @Eric: Don't use `DisplayFor` at all. – SLaks Dec 05 '12 at 22:11
  • Sorry, I misspoke. I meant `Display()`. However, after re-reading your reply, I now understand that you meant to literally just write `@Model.Address.TwoLine` without any `@Html.Display()`. This did work. However, it does drive me to ask... why EVER use `Display` or `DisplayFor`? – Eric K Dec 05 '12 at 22:29
  • 1
    @Eric: `DisplayFor()` allows you to write your own display templates that turn aribtrary types into markup. (which is probably what you should be doing here) – SLaks Dec 05 '12 at 22:32
  • Any good resources for learning that? I'm new to MVC, so its been a huge gear change from web forms. – Eric K Dec 05 '12 at 23:17