What does @ do when it's already inside the code (as opposed to internal markup)?

I read in Stephen Sanderson's book about ASP.NET, and I reached a point where I really got confused.

Work

@foreach (var link in Model) { @Html.RouteLink(link, new { controller = "Product", action = "List", category = link, page = 1 }); } 

Does not work

 @foreach (var link in Model) { Html.RouteLink(link, new { controller = "Product", action = "List", category = link, page = 1 }); } 

(The difference is the first character inside the block)

In both scenarios, Razor gets this code, not markup (HTML), so why did I have to put the @ symbol at the beginning? What is the difference and what am I missing?

Edit:

I have to clarify what is not working. This menu and link is the current category. Now it works fine with @ , and you can see links to categories, but without it, as if there are no categories .. you don’t see anything.

+4
source share
4 answers

Inside the foreach parser automatically works if it is in code mode or razor template mode, which allows you to output html, razor or code.

The difference between the two statements is that one is in razor-pattern mode (works) and the other is in code mode (doesn't work)

Html.RouteLink returns MvcHtmlString , in the second example (in code mode) you execute a function and do nothing with the returned MvcHtmlString , so nothing is displayed when the page is requested.

In the first example, it works in razor template mode, when you do @Html.RouteLink , it is added to the razor template, and the razor correctly interprets this and displays your link for you.

+2
source

When you use a semicolon; (or without @) it executes a line of code, but the return is not written to the response stream, while without it and using @ it returns the result (MvcHtmlString) directly to the response stream at this point.

+2
source

@ in this example indicates that you want to output the result of the instruction to the user. Similar to Response.Write() .

When the @ sign is omitted, the function returns the result, but since it is not assigned or sent anywhere, it is lost.

+2
source

Keep in mind that you can have html inside this foreach block:

Works:

 @if (someConditionalExpression) { <p>Only shown if the conditional was true.</p> } 

Since the markup here is also legal, you need to use the @ symbol to indicate to the viewer that you want the code again, and not the markup. Otherwise, it is ambiguous that you wanted.

0
source

All Articles