Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 715
Baggerz Avatar asked Dec 14 '22 19:12

Baggerz


1 Answers

This does the trick for me:

Controller:

public ActionResult Index()
{
    var stringArray = new string[3] { "Manual", "Semi", "Auto"};
    ViewBag.Collection = stringArray;
    return View();
}

View:

    @foreach(var str in ViewBag.Collection)
    {
        @Html.Raw(str); <br/>
    }

    @for (int i = 0; i <= 2; i++ )
    {
        @Html.Raw(ViewBag.Collection[i]) <br/>
    }

Output:

enter image description here

Sorry for not using your terms. I was scrachting this together from the top of my head.

like image 103
Marco Avatar answered Dec 31 '22 03:12

Marco