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.
In a Razor code block, @
means print this value out. In this particular case, without the @
you are not telling Razor to do anything, you are simply inserting a property name in place of a statement.
This is why the @
will correct in this case. It has a different meaning than "mark a code block".
As a side note, you can also use @
to mark a literal block:
@:speaker.Name;
would also "correct" it, by printing out, literally "speaker.Name;" instead of its value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With