2

This question appear when I worked with partial view (MVC3/Razor), but I am sure - it's clear Razor Syntax question, not related direct to partial view. So - I have partial view Menu.cshtml with full markup as:

@model IEnumerable<SportsStore.WebUI.Models.NavLink>
@foreach(var link in Model)
{
    @Html.RouteLink(link.Text, link.RouteValues);
}

No problem - "parent" view call it @{Html.RenderAction("Menu", "Nav");} and all work as magic. But, if I will edit the Menu.cshtml as:

@model IEnumerable<SportsStore.WebUI.Models.NavLink>
@foreach(var link in Model)
{
    Html.RouteLink(link.Text, link.RouteValues);
}

(see - NO '@' before Html.RouteLink!) all just broke: now @{Html.RenderAction("Menu", "Nav");} output is totally empty, no one HTML tag.

Want to know - what is the difference between two piece of code? I assume @ before foreach also automatically "drop into" and apply to Html.RouteLink as well? So - am I wrong?

1
  • You sir, are my hero. I'm working through the same SportsStore article it seems, but I'm converting to VB.Net on the fly. The conversion between C# and VB is usually trivial, but with Razor it can be tricky. I was having the same issue with RouteLink not creating output, it seems VB.Net suffers the same flaw (read: applies the same logic)... I added the @ and everything clicked into gear again. THANK YOU @Smarty Commented Aug 3, 2011 at 12:25

2 Answers 2

3

The @ before the statement causes it to be written to the output stream. When you remove it, all you are doing is invoking a method call on the Html object.

The @-operator's purpose is two-fold. It can either be used to output an expression to the response stream like you see it used in the first example. The other function is to start a code block. You can see this second behavior used in your code example with the @foreach(var link in Model)

Sign up to request clarification or add additional context in comments.

1 Comment

That is it! Now I confident with @ operator. :)
3

The Html.RouteLink method simply returns an IHtmlString containing a link; it doesn't do anything else.

When you write @Html.RouteLink(...), you're printing this link to the page.
When you write Html.RouteLink(...), you're calling the method without doing anything with the link.
Thus, nothing happens.

1 Comment

Very good explanation, thanks a lot! It's a pity I can't mark both Answers with green mark.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.