3

I need to pass some information to a partial cshtml view. I use a ViewDataDictionary and the ViewBag for that.

public ActionResult TaskPage(int ID = 0)
{
    ViewBag.breadcrumbs = new string[] {
        "List", "Tasks"
    };
    ViewBag.title = "Editing - My selected itemd";
    ViewBag.id = ID;
    return View();
}

and then when assembling the view I pass a ViewDataDictionary as well:

@Html.Partial("~/Views/Components/_Header.cshtml", new ViewDataDictionary { { "role", "task-page" } })

My _Header.cshmtl file uses both this dictionary and the ViewBag.

  ViewBag.breadcrumbs = ViewBag.breadcrumbs != null ? ViewBag.breadcrumbs : new string[] { };
  var role = ViewData["role"];

To my surprise, the ViewBag does not contain any data when I pass the ViewDataDictionary as well. How is that possible? Any idea how to better handle this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
nest
  • 1,385
  • 1
  • 15
  • 34
  • What do you mean by "already in the ViewBag"? ViewBag is only kept for the life of one request. You can't put something in ViewBag, make a request, then expect it to be there in the next request. – Erik Funkenbusch Mar 31 '15 at 14:38
  • The ViewBag is filled on the Controller. I added the specific code to clarify. – nest Apr 01 '15 at 09:58
  • 1
    Looks like this one: http://stackoverflow.com/questions/5729784/cant-access-viewbag-in-a-partial-view-in-asp-net-mvc3 – Daniel Stackenland Apr 01 '15 at 12:03
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Apr 01 '15 at 12:54
  • Ok. How can I let other viewers know they can find the solution in this post since nobody posted an actual answer? – nest Apr 01 '15 at 12:56
  • In fact, you can post an answer. – John Saunders Apr 01 '15 at 13:21

1 Answers1

2

See this post What's the difference between ViewData and ViewBag?

It would appear that "Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary." which would suggest that you are overwriting the ViewBag when you pass a new ViewDataDictionary object

Taken from this blog post

public dynamic ViewBag 
{ 
    get 
    { 
         if (_dynamicViewData == null) 
        {
            _dynamicViewData = 
            new DynamicViewDataDictionary(() => ViewData); 
        }
        return _dynamicViewData;
    }
} 
Community
  • 1
  • 1
ste-fu
  • 6,879
  • 3
  • 27
  • 46