Question

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>                                        
Was it helpful?

Solution

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.

OTHER TIPS

Maybe I didn't understand your question in which case please correct me but can't you simply:

@Html.ActionLink(page, "Question", new { id = Model.Question.Id, page = page })

This may be correct :

href="@(action)"> @page 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top