1

Recently I am coding in a cshtml file in a ASP.NET MVC project. Following code is odd and I cannot understand Why does Razor still need prefix '@' before @Html.DropDownListFor?

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
{
……
   for (var i = 0; i < Model.TotalLevel; i++)
        {
            if (i != 0)
            {
                @Html.DropDownListFor(x => x.SelectedDepartmentIds[i], Enumerable.Empty<SelectListItem>(), "string", new {@class = "hidden department"})
                    ;
            }
            else
            {
                @Html.DropDownListFor(x => x.SelectedDepartmentIds[i], Model.Departments, "string", new {@class = "department"})
                    ;
            }
        }
}

According to Unexpected "foreach" keyword after "@" character , @Html.DropDownListFor(x => x.SelectedDepartmentIds[i], Enumerable.Empty<SelectListItem>(), "string", new {@class = "hidden department"}) is indeed inside c# source, so there is no need to add @before the statement. However, if not, the view didn't display drowdown list. So in fact @ is needed before Html though it's in c# source.

Anyone can tell me why? Is the accepted answer from Unexpected "foreach" keyword after "@" character miss something?

Community
  • 1
  • 1
guo
  • 9,674
  • 9
  • 41
  • 79
  • 1
    `Html.DropDownListFor()` would just execute the method (it would not return anything). The leading `@` means that the result of method is rendered in the view –  Feb 13 '17 at 05:42
  • @StephenMuecke Could you please offer some official url verifying that? – guo Feb 13 '17 at 06:31
  • Perhaps [this](https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor) and [this](https://www.mikesdotnetting.com/article/258/usage-of-the-at-sign-in-asp-net) might help. Without the leading `@` , you would need to assign the return value of `Html.DropDownListFor()` (a `MvcHtmlString`) to a variable and then output the result to the view - `@{ var ddl = Html.TextBoxFor(m => m.ID); @ddl }` –  Feb 13 '17 at 07:02

0 Answers0