如何为单个视图分配多个模型?

时间:2009-01-20 23:57:53

标签: asp.net-mvc

我有一个城市列表和一个国家/地区列表,我想在视图(aspx)文件中找到它们。我正在尝试这样的事情,但它不起作用:

命名空间World.Controllers {     公共类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>

1 个答案:

答案 0 :(得分:4)

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

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