serge
serge

Reputation: 15219

using Html.Encode in Razor

I have the following sample code in a razor view on a MVC4 sample project:

<p>@((@Model == null) ? "<unknow man>" : @Model.ClientName)</p>
<p>
    @if (@Model == null)
    {
        @Html.Encode("<unknow man>")
    }
    else
    {  
        @Model.ClientName;
    }
</p>

The output is a little bit odd for me...

In Internet Explorer I see:

<p>&lt;unknow man&gt;</p>
<p>&amp;lt;unknow man&amp;gt;</p>

In Chrome:

<p>​<unknow man>​</p>
​<p>​&lt;unknow man&gt;</p>​

And what is the most incredible (for me) is that finally I have the same visual output:

<unknow man>

&lt;unknow man&gt; 

I wanted to display, however, this one in HTML:

<p>&lt;unknow man&gt;</p>
<p>&lt;unknow man&gt;</p>

and this one to the user:

<unknow man>

<unknow man>

PS

I found a solution, finally, to display properly the string, like this

    @if (@Model == null)
    {
        @("<unknow man>")
    }

But who can explain me the difference for the HTML.Encode in browsers, and why this didn't work like coded in the first example?

Upvotes: 0

Views: 5785

Answers (1)

Gregoire
Gregoire

Reputation: 24832

<p>@((@Model == null) ? @Html.Raw("&lt;unknow man&gt;") : @Model.ClientName)</p>
<p>
    @if (@Model == null)
    {
        <text>&lt;unknow man&gt;</text>
    }
    else
    {  
        @Model.ClientName;
    }
</p>

Upvotes: 0

Related Questions