迭代List <object>

pea*_*ber 4 c# asp.net-mvc

如何遍历Object类型的List?

List<object> countries = new List<object>();
countries.Add(new { Name = "United States", Abbr = "US" , Currency = "$"});
countries.Add(new { Name = "Canada", Abbr = "CA", Currency = "$" });
...more
Run Code Online (Sandbox Code Playgroud)

我想在我的视图中做一些事情(使用属性名称)

@model ViewModel
@foreach(object country in Model.Countries)
{
    Name = country.Name
    Code = country.Abbr
    Currency = country.Currency
}
Run Code Online (Sandbox Code Playgroud)

更新:忘了提到我正在使用MVC,我想在View中循环数据.States对象是ViewModel要查看的强类型属性之一.

更新:按要求更新以显示如何从控制器调用View -

[HttpPost]
public ActionResult Index(FormCollection form)
{
..some validations and some logic
ViewModel myViewModel = new ViewModel();
myViewModel.Countries = GetCountries(); -- this is where data get initialized
myViewModel.Data = db.GetData();
return PartialView("_myPartial", myViewModel);
}
Run Code Online (Sandbox Code Playgroud)

L.B*_*L.B 6

var countries = new []{
        new { Name = "United States", Abbr = "US", Currency = "$" },
        new { Name = "Canada", Abbr = "CA", Currency = "$" }
    };

foreach(var country in countries)
{
      var Name = country.Name;
      .....
}
Run Code Online (Sandbox Code Playgroud)


kba*_*che 3

如果我理解得很好,您正在尝试将视图模型从控制器发送到视图。所以如果你使用剃刀你的代码应该是这样的

@model ViewModel
@foreach(object country in Model.countries)
{
  var Name = country.Name
  var Code = country.Abbr
  var Currency = country.Currency
}
Run Code Online (Sandbox Code Playgroud)

注意关键字Model

编辑

// Code inside your controller should be like this
ViewModel myModel = new ViewModel();
List<object> countries = new List<object>();
countries.Add(new { Name = "United States", Abbr = "US" , Currency = "$"});
countries.Add(new { Name = "Canada", Abbr = "CA", Currency = "$" });

myModel.countries = countries;

return View("yourView", myModel); // you can write just return View(myModel); if your view's name is the same as your action 
Run Code Online (Sandbox Code Playgroud)

希望对您有帮助。