列出元素时出错

时间:2014-11-16 07:55:16

标签: asp.net-mvc

我收到以下错误

  

传递到字典中的模型项的类型为'System.Collections.Generic.List 1[<>f__AnonymousType3 4 [System.String,System.Int32,System.Int32,System.DateTime]]',但是这个字典需要'System.Collections.Generic.IEnumerable`1 [ControllerName]'类型的模型项。

之后我做了代码迁移(数据库更新),我想按列名列出项目我的代码如下

public ActionResult Index()
{
  DB db = new DB();
  var categorylist = from a in db.categories
                     select new
                     {
                       a.CategoryName, 
                       a.ID, 
                       a.stock, 
                       a.EntryDate
                     };
  return View(categorylist.ToList());
}

任何帮助将不胜感激

提前致谢。

查看如下

@model IEnumerable<Categories.Models.Categories>
@{
  ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
  @Html.ActionLink("Create New", "Create") </p> <table class="table">
  <tr>
    <th>@Html.DisplayNameFor(model => model.CategoryName)</th>
    <th>@Html.DisplayNameFor(model => model.stock)</th>
    <th>@Html.DisplayNameFor(model => model.EntryDate)</th>
    <th></th>
  </tr>
  @foreach (var item in Model) {
  <tr>
    <td>@Html.DisplayFor(modelItem => item.CategoryName)</td>
    <td>@Html.DisplayFor(modelItem => item.stock)</td>
    <td>@Html.DisplayFor(modelItem => item.EntryDate)</td>
    <td>
      @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
      @Html.ActionLink("Details", "Details", new { id=item.ID }) |
      @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
  </tr> 
}
</table>

2 个答案:

答案 0 :(得分:3)

要利用MVC的模型绑定功能,您应该创建一个视图模型,表示要显示和/或编辑的属性(根据需要调整属性类型)

public class CategoryVM
{
  public int ID { get; set; } 
  public string CategoryName { get; set; }
  public int Stock { get; set; }
  public DateTime EntryDate { get; set; }
}

并将方法更改为

public ActionResult Index()
{
  DB db = new DB();
  var categorylist = (from a in db.categories
                 select new CategoryVM
                 {
                   CategoryName = a.CategoryName, 
                   ID = a.ID, 
                   Stock = a.stock, 
                   EntryDate = a.EntryDate
                 }).ToList();
  return View(categorylist);
}

查看

@model List<CategoryVM>
<table>
  <thead>
    <tr>
      <th>Category Name</th>
      <th>stock</th>
      <th>Entry Date</th>
      ...
    </tr>
  </thead>
  <tbody>
    @foreach(var item in Model)
    {
      <tr>
        <td>@Html.DisplayFor(m => item.ID)<td>
        <td>@Html.DisplayFor(m => item.CategoryName)</td>
        ...
      </tr>
    }
  </tbody>
</table>

答案 1 :(得分:0)

我认为您需要更改在视图中定义的模型类型

修改:尝试

@model IList<dynamic>