Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor syntax error "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"

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.

like image 592
haansi Avatar asked Dec 17 '13 00:12

haansi


2 Answers

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.

like image 109
p.s.w.g Avatar answered Nov 16 '22 06:11

p.s.w.g


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

like image 4
Sklivvz Avatar answered Nov 16 '22 07:11

Sklivvz