문제

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.

도움이 되었습니까?

해결책

Have you tried

ViewBag.SuccessBody = TempData["successBody"];

다른 팁

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

ViewBag.SuccessBody = TempData["successBody"];
ViewData["SuccessBody"] = TempData["successBody"];

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"]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top