使用与主视图不同的表的局部视图

时间:2012-09-13 07:18:15

标签: asp.net-mvc-3 razor partial-views

我正在尝试将一个下拉列表添加到我的酒店视图 - index.cshtml。此视图的酒店控制器获取酒店对象:

private HotelEntities db = new HotelEntities();

   public ViewResult Index()
    {
        var hotels = db.Hotels.Include("Address");
        return View(hotels.ToList());
    }

我想在此视图中显示酒店列表。但在显示此列表之前,我希望用户能够搜索他们想要查看酒店的国家/地区。 下拉列表是我数据库中的国家/地区列表。我的实体模型中有一个对象 - HotelEntities。 我在共享文件夹中创建了一个部分国家/地区视图,其中包含下拉列表和一个获取国家/地区列表的国家/地区控制器:

 public class CountryController : Controller
   {
    private HotelEntities db = new HotelEntities();
    //
    // GET: /Country/

    public ActionResult Index()
    {
        var country = db.Countries.ToList();
        return View(country.ToList());
    }

}

在部分视图中我有:

@model IEnumerable <MvcApp20Aug.Models.Country>


           @foreach (var item in Model)
           {
             @Html.DropDownListFor(model => item.CountryId, new SelectList(item.CountryIso, item.CountryName));

           }

最后我将局部视图添加到我的酒店index.cshtml:

@model IEnumerable<MvcHotelApp.Models.Hotel>

@{
    ViewBag.Title = "Index";
}

<h2>Index </h2> 
@{Html.RenderPartial("Country");}
<p>

我收到错误:传入字典的模型项的类型为'System.Collections.Generic.List`1 [MvcHotelApp.Models.Hotel]',但此字典需要类型为'MvcHotelApp.Models的模型项.Country”。

所以我不明白如何在我的局部视图中使用不同的表到我的主视图。 任何人都可以解释为什么不这样做以及我应该如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

称之为,

         @{Html.RenderAction("Index","Country");}

并改变你country这样的部分视图,

       @model IEnumerable <MvcApp20Aug.Models.Country>
         @Html.DropDownListFor("CountryId", new SelectList(Model.CountryIso, Model.CountryName));