Asp.net mvc 如何将多个模型指定给单个视图?

Asp.net mvc 如何将多个模型指定给单个视图?,asp.net-mvc,Asp.net Mvc,我有一个城市列表和一个国家列表,我想把它们都放在view aspx文件中。我正在尝试类似的方法,但不起作用: 命名空间世界.控制器{ 公共类控制器:控制器{ 公共行动结果指数{ List<Country> countryList = new List<Country>(); List<City> cityList = new List<City>(); this.ViewData["CountryL

我有一个城市列表和一个国家列表,我想把它们都放在view aspx文件中。我正在尝试类似的方法,但不起作用:

命名空间世界.控制器{ 公共类控制器:控制器{ 公共行动结果指数{

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

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

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