2009-01-20 69 views
1

我有一个城市的列表和国家的列表,他们都希望对视图(aspx)文件有。我想这样的事情,但它不工作:如何将多个模型分配到单个视图?

命名空间World.Controllers { 公共类WorldController:控制器{ 公众的ActionResult指数(){

 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

您需要获取您按名称设置的视图数据。 I.E.

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

但这并不理想,因为它没有强类型。我会建议创建一个特定于您的视图的模型。

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

然后创建您的视图强类型为WorldModel视图。然后在动作:

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

只要确保你的看法是强类型:

public partial class Index : ViewPage<WorldModel> 

你就可以这样来做:

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