MasterMastic
MasterMastic

Reputation: 21306

What does @ do when it's already inside code (in contrast to inside markup)?

I'm reading in Steven Sanderson's book about ASP.NET and I've reached a point where I'm really confused.

Works

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

Doesn't work

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

(Difference is the first character inside the block)

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

Edit:

I should clarify what doesn't work. It's a menu and link is the current category. Now, with @ it works fine and you can see the links to the categories, but without it, it's as if there are no categories.. you don't see anything.

Upvotes: 4

Views: 152

Answers (4)

Kami
Kami

Reputation: 19457

The @ in this instance indicates that you want to output the result of the statement to the user. Similar to Response.Write().

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

Upvotes: 2

Chris Diver
Chris Diver

Reputation: 19852

Inside the foreach the parser automagically works out if it is in code mode or razor template mode, allowing you to output html, razor or code.

The difference between the two statements is one is in razor template mode (working) and the other is in code mode (not working)

Html.RouteLink returns an MvcHtmlString, in your second example (in code mode) you execute a function and do nothing with that MvcHtmlString that is returned, so nothing is rendered when you request the page.

In the working first example, it's in razor template mode, when you do @Html.RouteLink it is added to the razor template, and razor interprets that correctly and renders your link for you.

Upvotes: 2

Joel Coehoorn
Joel Coehoorn

Reputation: 416141

The thing to remember is that you can have html inside that foreach block as well:

Works:

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

Since markup is also legal here, you need to use the @ symbol to indicate to the view engine that you want code again, rather than markup. Otherwise, it's ambiguous which you wanted.

Upvotes: 0

Zach
Zach

Reputation: 3207

When you use the semicolon ; (or without the @) it's executing a line of code but the return is not written to the response stream, whereas without it and by using the @ it is returning a result (MvcHtmlString) directly to the response stream at that point.

Upvotes: 2

Related Questions