Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through List<object>

Tags:

c#

asp.net-mvc

How can I loop through a List of type Object?

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

I want to do something like (using property names) in my view

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

UPDATE: Forgot to mention that I am using MVC and I want to loop the data in View. Countries object is one of the property of ViewModel to view is strongly typed.

UPDATE: updating as asked to show how View is called from the controller -

[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);
}
like image 804
peacefulmember Avatar asked Dec 05 '22 14:12

peacefulmember


2 Answers

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;
      .....
}
like image 99
L.B Avatar answered Dec 10 '22 09:12

L.B


If I understood well, you are trying to send the view model from the controller to the view. So if you are using razor your code should be like this

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

notice the keyword Model.

Edit

// 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 

Hope it helps you.

like image 34
kbaccouche Avatar answered Dec 10 '22 10:12

kbaccouche