Search code examples
htmlasp.net-mvcrazorviewbag

Access a Viewbag like an Array?


Imagine a view bag called

 ViewBag.Modes

this contains the following:

Simple
Advanced
Manual
Complete

How can I access the viewbag by index like you would in an array?

e.g Simple is at index 0 then it would look like this

ViewBag.Modes[0]

I tried the above but it doesn't work so...How can I replicate this with viewbag or is there a workaround I can use?


Solution

  • Thanks for the posts but shortly after writing this I came up with this solution using a model & list as below this could also be done using viewbag instead of model.

    List<string> list = new List<string>();
                foreach (Models.AppModeInfo blah in Model.theAppModes)
                {
                    list.Add(blah.Name);
                }
    
                var AppModeText = "";
                switch (item.AppModeId)
                {
                    case 1:
                        AppModeText = list[0];
                        break;
                    case 2:
                        AppModeText = list[1];
                        break;
                    case 3:
                        AppModeText = list[2];
                        break;
                    case 4:
                        AppModeText = list[3];
                        break;
                    case 5:
                        AppModeText = list[4];
                        break;
                }