ASP.Net MVC and MVC Core Error 500 after editing cshtml Razor page

I’ve had this pop up a few times over the years when editing razor synctax cshtml files. There is some perfectly legal c# code that even compiles fine in your razor files, but will fail when you try to run it- specifcally, when you do this in c#:

if(condition == true)
something = somethingelse;

Perfectly legal to do a single line of code following a conditional statement. However, when this is run inside a code block in a razor/cshtml file, it will fail! So you always have to enclose your code block in enclosing braces like so:
if(condition == true)
{
something = somethingelse;
}

I feel like this was overlooked in razor version 0.1 or something and was never corrected later. It would be nice if it at least failed during compile time.

Leave a Reply

Your email address will not be published.