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

3

41

When I try to assign a value to the ViewBag I get the following error:

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

My code is as follows:

public ActionResult Success()
{
   ViewBag["SuccessBody"] = TempData["successBody"];
   return View();
}

PS: Why I do this you may ask? Because I am redirecting to the Success action and I needed something that persists across redirects. Then, I am assigning the value to ViewBag in order to pass the Value to a 'shared' view.

Aboard answered 20/12, 2013 at 20:40 Comment(4)
But you can just use TempData. It will survive for one redirect.Wagonage
Yes, but unfortunately shared views do not support the TempData objects.Aboard
What version of Visual Studio are you using to compile this code?Allyson
I am using Visual Studio 2012, upd4.Aboard
A
54

Have you tried

ViewBag.SuccessBody = TempData["successBody"];
Alicealicea answered 20/12, 2013 at 21:15 Comment(4)
What's the reason you can't use an indexer?Lebanon
DynamicObjects do not expose their children as an array directly. This is just how it was designed. msdn.microsoft.com/en-us/library/…Alicealicea
Ah I see, it's easy to miss. So a ViewBag can access them as dynamic properties, while ViewData can access them with an indexer?Lebanon
Yes, Viewdata is a ViewDataDictionary which implements the interface IDictionary. That is why you can use an indexer on it.Alicealicea
C
32

ViewBag is a dynamic wrapper for ViewData, so these two statements are the same:

ViewBag.SuccessBody = TempData["successBody"];
ViewData["SuccessBody"] = TempData["successBody"];
Cornhusk answered 20/12, 2013 at 21:17 Comment(0)
L
9

ViewBag and ViewData seem kind of interchangable, but there are different rules as to how you access the data inside of them. Your issue pops up when you try to index into a ViewBag, which doesn't work.

For ViewBag, you dereference the items with a dot, like this.

ViewBag.MyItem

However, with ViewData, you access the items by indexing the appropriate key from the key value dictionary like this.

ViewData["MyItem"]

Linearity answered 8/4, 2019 at 3:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.