Thomas
Thomas

Reputation: 8013

Razor code between double quotes

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>                                        

Upvotes: 10

Views: 16283

Answers (3)

D S
D S

Reputation: 47

This may be correct :

href="@(action)"> @page 

Upvotes: 3

Buildstarted
Buildstarted

Reputation: 26689

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.

Upvotes: 21

Darin Dimitrov
Darin Dimitrov

Reputation: 1039528

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 })

Upvotes: 8

Related Questions