Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag- MVC3-ASP.NET

I am tring to assign a value to ViewBag in the controller for later usage in the View, It complaines with the following error.

Assigning the value in the Controller like this.

 ViewBag["isAdmin"]=true;

Error:

 Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'

Does anyone had this before?

like image 773
Hari Gillala Avatar asked Jun 24 '11 10:06

Hari Gillala


2 Answers

All you need is ViewBag.isAdmin = true. the you can access is with

if(ViewBag.isAdmin)
{ 
    //do stuff
}
like image 91
TheRealTy Avatar answered Sep 28 '22 08:09

TheRealTy


As a follow-up, the idea behind ViewBag (and ViewData) is that you can store off key-value pairs of stuff and conveniently access them over in the View.

With ViewData, you reference these things like so:

ViewData["SomeKey"] = someObject;

If you want to do the same using the ViewBag instead (which provides a wrapping around that ViewData dictionary construct and makes it a little less verbose and a bit more readable) you reference things like so:

ViewBag.isAdmin = true;

and can check them, as tyrongower stated above, like so:

if (ViewBag.isAdmin)
{
   // do stuff
}

I typically use the ViewBag syntax when I do use this construct, but they really do reference the same stuff. So if you did something like so outside the View:

ViewData["isAdmin"] = true;

you could reference it like this, if you were so inclined:

ViewBag.isAdmin

or vice-versa.

Just a little more detail on the concept.

like image 37
itsmatt Avatar answered Sep 28 '22 08:09

itsmatt