【问题标题】:Partial view using a different table to that of the main view使用与主视图不同的表的局部视图
【发布时间】:2012-09-13 07:18:14
【问题描述】:

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

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”类型的模型项.国家'。

所以我不明白如何在我的部分视图中使用与主视图不同的表。 谁能解释为什么不这样做以及我应该如何处理这个问题。

【问题讨论】:

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


    【解决方案1】:

    这样称呼,

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

    像这样改变你country partialview,

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

    【讨论】:

    • 谢谢,我现在收到错误执行处理程序“System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper”的子请求时出错。有什么想法吗?
    • 抱歉,也忘了提及您的局部视图的更改,更新了我的答案,请立即查看。
    • @Charlie,那你可能需要自己调试了。
    • @model MvcApp20Aug.Models.Country @Html.DropDownList("CountryList", new SelectList(Model.CountryIso, Model.CountryName));以上在国家视图中工作感谢您的帮助
    猜你喜欢
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多