Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>                                        
like image 722
Thomas Avatar asked Nov 22 '10 20:11

Thomas


People also ask

How do you put a double quote in code?

To place quotation marks in a string in your code In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.

What do double quotes mean in code?

In JavaScript, single (' ') and double (“ ”) quotes are frequently used for creating a string literal. Generally, there is no difference between using double or single quotes, as both of them represent a string in the end.

How do you pass a double quote in a string?

If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.


3 Answers

This may be correct :

href="@(action)"> @page 
like image 191
D S Avatar answered Nov 13 '22 06:11

D S


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.

like image 34
Buildstarted Avatar answered Nov 13 '22 07:11

Buildstarted


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 })
like image 8
Darin Dimitrov Avatar answered Nov 13 '22 06:11

Darin Dimitrov