开发者

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 i开发者_如何学编程ndexing with [] to an expression of type 'System.Dynamic.DynamicObject'

Does anyone had this before?


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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜