tags:

views:

86

answers:

1

I have a list of cities and a list of countries and both of them I want to have on the view (aspx) file. I'm trying something like this but it's not working:

namespace World.Controllers { public class WorldController : Controller { public ActionResult Index() {

  List<Country> countryList = new List<Country>();
  List<City> cityList = new List<City>();

  this.ViewData["CountryList"] = countryList;
  this.ViewData["CityList"] = cityList;

  this.ViewData["Title"] = "World Contest!";
  return this.View();
 }
}

}

<table>
<% foreach (Country country in this.ViewData.Model as IEnumerable) { %>
 <tr>
  <td><%= country.Code %></td>
 </tr>
<% } %>
</table>
+4  A: 

You need to get the view data you've set by name. I.E.

<table>
<% foreach (Country country in (List<Country>)this.ViewData["CountryList"]) { %>
        <tr>
                <td><%= country.Code %></td>
        </tr>
<% } %>
</table>

But that's not ideal, because it's not strongly typed. What I would suggest is creating a model specific to your view.

public class WorldModel
{
    public List<Country> Countries { get; set; }
    public List<City> Cities { get; set; }
}

And then creating your view strongly typed as a WorldModel view. Then in your action:

List<Country> countryList = new List<Country>();
List<City> cityList = new List<City>();
WorldModel modelObj = new WorldModel();
modelObj.Cities = cityList;
modelObj.Countries = countryList;

this.ViewData["Title"] = "World Contest!";
return this.View(modelObj);

Just make sure that your view is strongly typed:

public partial class Index : ViewPage<WorldModel>

And you'll be able to do it this way:

<table>
<% foreach (Country country in ViewData.Model.Countries) { %>
        <tr>
                <td><%= country.Code %></td>
        </tr>
<% } %>
</table>
Odd