English 中文(简体)
如何为单个视图分配多个模型?
原标题:
  • 时间:2009-01-20 23:57:53
  •  标签:

我有一个城市列表和一个国家列表,我想将它们都放在视图(aspx)文件中。我正在尝试这样做但不起作用:

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();
    This is already in Chinese.
This is already in Chinese.

This is already in Chinese.

<table>
<% foreach (Country country in this.ViewData.Model as IEnumerable) { %>
    <tr>
        <td><%= country.Code %></td>
    </tr>
<% This is already in Chinese. %>
</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>
问题回答

暂无回答




相关问题
热门标签