如何循环遍历对象类型的列表?
List<object> countries = new List<object>();
countries.Add(new { Name = "United States", Abbr = "US" , Currency = "$"});
countries.Add(new { Name = "Canada", Abbr = "CA", Currency = "$" });
...more
在我看来,我想做一些类似(使用属性名称)的事情
@model ViewModel
@foreach(object country in Model.Countries)
{
Name = country.Name
Code = country.Abbr
Currency = country.Currency
}
更新:
忘了说我正在使用 MVC,我想在 View 中循环数据。 Country 对象是 ViewModel 的属性之一,用于查看强类型。
更新:
按要求更新以显示如何从控制器调用视图 -
[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);
}
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;
.....
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)