【问题标题】:How to assign multiple models to a single view?如何将多个模型分配给单个视图?
【发布时间】:2009-01-20 23:57:53
【问题描述】:

我有一个城市列表和一个国家列表,我希望在视图 (aspx) 文件中包含这两个列表。我正在尝试这样的事情,但它不起作用:

命名空间 World.Controllers { 公共类世界控制器:控制器{ 公共动作结果索引(){

        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>

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    您需要按名称获取已设置的视图数据。即。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多