31

I'm new in ASP.NET C# and I have problems with some things.

In PHP, I can store HTML code inside a variable, for example:

$list = "<li>My List</li>";
echo "<ul>{$list}</ul>"; // write <ul><li>My List</li></ul>

I tried this in ASP.NET and Razor

string List = "<li>My List</li>";
<ul>@List</ul>

But ASP changes "<" and ">" to &gt; and &lt;.. You know any solution for this?

I have another question, can I insert variable inside a quotes like PHP?

echo "<ul>{$list}</ul>";

2 Answers 2

52

The Razor engine HTML encodes strings by default, as you have noticed. To avoid this behavior, just use Html.Raw():

<ul>@Html.Raw(List)</ul>

Edit

To render a variable within a string, I suppose you could use string.Format:

@{ var someVariable = "world"; }
@string.Format("<div>hello {0}</div>", someVariable)

Although that seems like overkill (at least for this example) when you can just write:

<div>hello @someVariable</div>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks dude, it works. And the other question? I can write a variable inside quotes like php? Ill select correct answer in 9 mins, thanks again.
@Carasuman no prob, glad it helped -- see my update above, if that helps.
This also works: <span class="hidden" data-state="@(entry.Key)_Title"> Check out haacked.com/archive/2011/01/06/…
2

For ASP.NET Core 6.0 you can use MarkupString like this:

@((MarkupString) yourString)

Comments

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.