【问题标题】:MVC3 Razor - Models and ViewsMVC3 Razor - 模型和视图
【发布时间】:2012-05-27 00:24:15
【问题描述】:

我有一个创建列表并将其返回到我的视图的操作..

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 吗?

救命!

【问题讨论】:

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


    【解决方案1】:

    我不确定您为什么要调用这样的局部视图。如果是特定于客户的视图,为什么不将其放在 Views/Customer 文件夹下?请记住,ASP.NET MVC 更多的是约定。所以我会一直遵守约定(除非绝对有必要配置自己)以保持简单。

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

    CustomerCustomerList 模型/视频模型

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

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

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

    Views/Shared/DisplayTemplates 下有一个名为Customer.cshtml 的视图,包含此内容

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

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

    【讨论】:

      【解决方案2】:

      您的视图需要一个模型:

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

      您正在向它传递一个匿名列表:

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

      您应该更改您的视图以接受列表或在将列表中的哪个项目传递给视图之前确定应该使用它。请记住,只有 1 个项目的列表仍然是列表,不允许 View 猜测。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        相关资源
        最近更新 更多