MVC3剃刀 - 模型和视图

时间:2012-05-27 00:24:16

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

我有一个创建List的动作并将其返回给我的视图..

public ActionResult GetCustomers()
    {
        return PartialView("~/Views/Shared/DisplayTemplates/Customers.cshtml", UserQueries.GetCustomers(SiteInfo.Current.Id));
    }

在“〜/ Views / Shared / DisplayTemplates / Customers.cshtml”视图中,我有以下内容:

@model IEnumerable<FishEye.Models.CustomerModel>
@Html.DisplayForModel("Customer")

然后我进入“〜/ Views / Shared / DisplayTemplates / Customer.cshtml”视图:

@model FishEye.Models.CustomerModel
@Model.Profile.FirstName

我收到错误:

The model item passed into the dictionary is of type System.Collections.Generic.List`1[Models.CustomerModel]', but this dictionary requires a model item of type 'Models.CustomerModel'.

不应该在Customers.cshtml中为集合中的每个项目显示Customer.cshtml吗?

帮助!

2 个答案:

答案 0 :(得分:1)

您的观点期待单一模型:

@model FishEye.Models.CustomerModel  // <--- Just one of me

你传给它一个匿名名单:

... , UserQueries.GetCustomers(SiteInfo.Current.Id)  // <--- Many of me

您应该更改视图以接受列表,或者在将列表传递到视图之前确定列表中应该使用哪个项目。请记住,包含1个项目的列表仍然是列表,并且不允许查看。

答案 1 :(得分:1)

我不确定你为什么要调用这样的局部视图。如果是特定于客户的视图,为什么不将其放在Views/Customer文件夹下?请记住,ASP.NET MVC更像是约定。所以我总是坚持惯例(除非非常需要配置自己)以保持简单。

为了处理这种情况,我会这样做,

CustomerCustomerList型号/ Videmodel

public class CustomerList
{
    public List<Customer> Customers { get; set; }
    //Other Properties as you wish also
}

public class Customer
{
    public string Name { get; set; }
}

在action方法中,我将返回CustomerList类的对象

CustomerList customerList = new CustomerList();
customerList.Customers = new List<Customer>();
customerList.Customers.Add(new Customer { Name = "Malibu" });
// you may replace the above manual adding with a db call.
return View("CustomerList", customerList);

现在CustomerList.cshtml文件夹下应该有一个名为Views/YourControllerName/的视图。该视图应如下所示

@model CustomerList
<p>List of Customers</p>
@Html.DisplayFor(x=>x.Customers)

Customer.cshtml s下使用此内容

创建一个名为Views/Shared/DisplayTemplate的视图
@model Customer
<h2>@Model.Name</h2>

这将为您提供所需的输出。