jwatts1980
jwatts1980

Reputation: 7356

Write HTML to page in MVC 4

I have some HTML stored in the database that looks exactly like this:

<strong><a href="http://www.google.com" target="_blank">Maintenance scheduled </a></strong>tomorrow

I want to output that to the Razor view properly formatted as HTML. I do not want to see the < and >, I just want the HTML.

You can see from this snippet that I've tried several different things:

div id="maintenanceMessage">
            @*@HttpUtility.HtmlDecode(sysSettings.MaintenanceMessage)*@
            @*@HttpUtility.HtmlDecode((new HtmlString(sysSettings.MaintenanceMessage)).ToString())*@
            @Html.Raw(sysSettings.MaintenanceMessage)
</div> 

But in every case it keeps showing it as text:

<strong><a href="http://www.google.com" target="_blank">Maintenance scheduled </a></strong>tomorrow

and not formatted HTML. I'm not sure what I am doing wrong?

Upvotes: 1

Views: 687

Answers (3)

Edgar Froes
Edgar Froes

Reputation: 778

Check your stored content. Maybe when you tried to store it in the database, it got the special HTML characters replaced with encoding characters. For example:

In the Unicode format, every < sign from the HTML tags would be replaced with the &#60; character.

It's better to store the raw HTML then the encoded HTML, so you won't have to deal with Coding/Encoding conversions.

Upvotes: 0

Matt Bodily
Matt Bodily

Reputation: 6423

if you replace the ascii before sending it to the view does it work. we send our strings through these

public string Decode(string value)
    {
        return (value)
            .Replace("&quot;", "\"")
            .Replace("&lt;", "<")
            .Replace("&gt;", ">");
    }

    public string Encode(string value)
    {
        return (value)
          .Replace("\"", "&quot;")
          .Replace("'", "''")
          .Replace("<", "&lt;")
          .Replace(">", "&gt;");
    }

Upvotes: 0

mxmissile
mxmissile

Reputation: 11673

Try

@MvcHtmlString.Create(HttpUtility.HtmlDecode(sysSettings.MaintenanceMessage))

Upvotes: 3

Related Questions