Razor code between double quotes

Thomas picture Thomas · Nov 22, 2010 · Viewed 14.2k times · Source

In a Razor View Engine template, I want to do the following: I want to put some code between the double quotes of an html attribute. The trouble is that the piece of code I want to insert contains some double quotes itself.

<a href="Url.Action("Item", new { id = Model.Item.Id, page = page });">@page</a>

You can easily see how things turn horribly wrong :-) I know i can calculate the link in a variable and then use it, but I'd rather not:

@{ var action = Url.Action("Question", new { id = Model.Question.Id, page = page }); }                   
<a href="@action">@page</a>                                        

Answer

Buildstarted picture Buildstarted · Nov 22, 2010

You don't need to escape or anything using Razor. Razor is smart enough to know when quotes are within attributes because you're escaping outside of html when you parse it.

<a href="@Url.Action("Item", 
       new { id = Model.Item.Id, page = page })">@page</a>

That code will work fine - Just make sure you have the @ symbol in front of the Url.Action call because if you don't it won't be parsed properly and I notice you don't have it in your question.

Edit: removed ; as Url.Action is not a statement.