I downloaded a sample project and noticed the author was using @ViewBag
when assigning data to ViewBag inside the controller, in all the examples I have seen ViewBag
was used but running the project I downloaded showed that using @ViewBag
works find so I am now a bit confused. Is there any difference between using @ViewBag
and ViewBag
inside the controller?
Asked
Active
Viewed 371 times
0

Matthew Verstraete
- 6,335
- 22
- 67
- 123
-
Are you sure this was in the controller and not in the view? – user247702 May 11 '14 at 15:19
-
Yes it was in the controller. – Matthew Verstraete May 11 '14 at 15:20
2 Answers
3
@ViewBag
works in the controller but it's not necessary, and likely a mistake from the author.
The reason it works is described in What's the use/meaning of the @ character in variable names in C#?, @
can be used to escape variable names that are also language keywords.

Community
- 1
- 1

user247702
- 23,641
- 15
- 110
- 157
-
Likewise i've seen folks write in Razor 1.0 @if (@myvar > 5). This does not work in latest Razor versions. – Yishai Galatzer May 11 '14 at 15:32
0
Are you sure @ViewBag in the controller? In Razor (the view engine asp .net mvc use) uses @ to indicate you want to write some c# code.
so essentially @ViewBag (use in Razor) and ViewBag (Use in controller) is the same thing.
for some basic razore rules, read this: http://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax

Alan Tsai
- 2,465
- 1
- 13
- 16