0

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?

1 Answer 1

1
<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>
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, however, I don't need the <text> node... see my update
@Serge the text node will not been rendered
thanks, a interesting variant, i tested, it works... see also my solution how about the Encode, why it didn't work?
@Serge: There will be two encodings: Html.Encode will done &lt;unknow man&gt; and @ will reencode your string so the & of &lt; and &gt; will be &amp;
if i put just Html.Encode (without @) I have no output at all..., So, you are trying to say that we can't use here Html.Encode function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.