Search code examples
asp.net-mvcasp.net-mvc-3razorhtml-helpermvchtmlstring

Return HtmlString From Model & Display Within View


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?


Solution

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