Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Razor Syntax: Is it an issue for razor to interpret @if(@Model

I am checking logs of exception and I came across an exception in lazy loading with glass mapper. I have a sitecore project with mvc and one of the views (shared cshtml) contains the following loop:

@foreach(var item in @Model.Collection)...

I would usually write:

 @foreach(var item in Model.Collection)...

I tried googling, but I found nothing. I have inherited this code from another guy, who I cannot contact. The website actually loads the page with no error. I've tried the same loop in pure MVC and it loads the page with no Error. However, I get this lazy loading issue that the entity is null there in logs (sitecore).

I will know more tomorrow, but I am curious regarding this. Has anyone came across such issue?

like image 804
nkalfov Avatar asked Dec 31 '25 09:12

nkalfov


1 Answers

I guess it works because C# allows the @ character at the beggining of a variable name (or any identifier, as @recursive pointed out in a comment). Actually this is used to allow having variable names that are also reserved words. After escaping the foreach, the code executed will look like:

foreach(var item in @Model.Collection)

And this is valid code in C#

like image 132
thepirat000 Avatar answered Jan 01 '26 23:01

thepirat000