I m declaring the following syntax in MVC Razor view:
@{
foreach (var speaker in Model)
{
speaker.Name;
}
}
and getting error
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
I am able to correct by adding a @
with speaker.Name;
but why it is ? I m sorry, I'm new to Razor but while I'm in code block @ {}
why I am required to use @ again. Even I m not mixing it with HTML ?
Help please.
Without the @
, the razor engine interprets speaker.Name;
as pure C#—that is, simply referencing a property, but not doing anything with it—but that won't compile. A statement which simply references a property by itself, without getting or setting its value, is not valid in C#.
Consider this razor
@foreach (var speaker in Model)
{
var name = speaker.Name;
@name
}
The first line is pure C#. It declares a variable, name
and initializes it with the value of speaker.Name
.
The second line is interpreted as a razor print directive, which prints the value of name
in the output.