Search code examples
arraysasp.net-mvcviewbag

MVC ViewBag Two Dimentional Array - How to access elements from controller


I have a simple MVC C# controller with 2 dimention array.

ViewBag.states = new SelectList(db.states, "state_code", "state_zone");

If state_code = "FL", I want to get its state_zone value in the controller

I tried:

int newZone = ViewBag.states["FL"].state_zone 

but I get error:

Cannot apply indexing with [] to an expression of type 'System.Web.Mvc.SelectList'

Any ideas?


Solution

  • Since ViewBag.states is dynamic property, you can't use indexer of SelectList against it because state_zone already stored inside Text property:

    int newZone = ViewBag.states["FL"].state_zone;
    

    Also this declaration seems possible but may throwing indexing error as described in comment:

    var zone = ViewBag.states as SelectList;
    
    int newZone = Convert.ToInt32(zone.Items[0].Text); // error: 'cannot apply indexing with [] to an expression of type 'System.Collections.IEnumerable'
    

    To use SelectList item indexer inside ViewBag object, you need to convert it into SelectList first, then use LINQ methods to reveal its value:

    var zone = ViewBag.states as SelectList;
    
    int newZone = Convert.ToInt32(zone.Skip(n).First().Text); // n = any index number
    
    // alternative:
    int newZone = Convert.ToInt32(zone.Where(p => p.Value == "[any_value]").First().Text);
    

    Similar issue:

    Get a text item from an c# SelectList