2012-05-27 148 views
0

我有一个创建一个列表,并返回给我看的动作..MVC3剃须刀 - 模型和视图

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

并在“〜/查看/共享/ DisplayTemplates/Customers.cshtml”的观点我有以下几种:

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

然后,我有在 “〜/查看/共享/ 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'. 

难道不应该显示Customer.cshtml在Customers.cshtml集合中的每一个项目?

帮助!

回答

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

而且在操作方法,我将返回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); 

现在应该有一个Views/YourControllerName/文件夹下称为CustomerList.cshtml视图。这种观点应该是这样的

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

有一个观点叫Customer.cshtmlViews/Shared/DisplayTemplate s的这个内容

@model Customer 
<h2>@Model.Name</h2> 

这会给你所需的输出。

+0

完美,谢谢这工作的魅力! –

+0

@JamesWoodley:不客气。很高兴我能帮上忙。 – Shyju

1

你的观点是期待一个单一的模式:

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

你传递一个匿名列表:

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

你应该改变你的观点,接受列表或确定适合该项目列表在传递给View之前应该被使用。请记住,有1个项目的列表仍然是一个列表,并且View不允许猜测。