user4593252
user4593252

Reputation: 3506

Razor, StringBuilder, HTML line break?

I have a problem that is just making me feel silly.... Given the following code in Razor:

@{
    ...
    if (purchasedEvent.Address != null && purchasedEvent.Address != String.Empty){
        addressBlock.AppendFormat("{0}<br />", purchasedEvent.Address); 
    }
    ...
}
@addressBlock.ToString()

The <br /> gets treated as literal text (that is to say I end up seeing something like 123 Cool Street<br />Anytown... rendered on the page. Changing the code (back) to addressBlock.AppendLine(purchasedEvent.Address) doesn't do any good either (renders 127 Cool Street Anytown.... What do I need to do to make the Razor engine respect that line break?

Upvotes: 3

Views: 2270

Answers (1)

Chris
Chris

Reputation: 27599

You need to use Html.Raw. To quote the docs: "Returns markup that is not HTML encoded."

So something like

@html.Raw(addressBlock.ToString())

The reason for it is that MVC is assuming that what you are giving it is the text as you want it to be seen and thus HTML encodes it. Raw allows you to tell it not to do that.

Upvotes: 3

Related Questions