MVC ViewBag 二维数组 - 如何从控制器访问元素

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

我有一个带有二维数组的简单 MVC C# 控制器。

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

如果state_code = "FL",我想在controller中得到它的state_zone

我试过:

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

但我收到错误:

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

有什么想法吗?

因为 ViewBag.states 是动态的 属性,你不能对它使用 SelectList 的索引器,因为 state_zone 已经存储在 Text 属性:

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

此声明似乎也可行,但可能会引发索引错误,如评论所述:

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'

要在 ViewBag 对象中使用 SelectList 项目索引器,您需要先将其转换为 SelectList,然后使用 LINQ 方法显示其值:

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);

类似问题:

Get a text item from an c# SelectList