【问题标题】:Foreach statement cannot operate on variables of type [Tracker.Models.INV_Assets]?Foreach 语句不能对 [Tracker.Models.INV_Assets] 类型的变量进行操作?
【发布时间】:2015-01-28 15:54:01
【问题描述】:

我正在整理一个相当简单的 Code-First MVC5 库存跟踪应用程序。我已将我的应用程序添加到 Seed() 和我的所有维护表(位置、供应商、状态等),我可以查看/创建/编辑/删除。我现在正在为我的主要 [INV_Assets] 模型处理 View,但是当尝试通过我的模型中的项目 foreach 在表格中显示所有 [INV_Assets] 时,我收到错误:foreach statement cannot operate on variables of type 'Tracker.Models.INV_Assets' because 'Tracker.Models.INV_Assets' does not contain a public definition for 'GetEnumerator'

下面是我[INV_Assets]的模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using GridMvc.DataAnnotations;
using System.Web.Mvc;
using Tracker.Models;

namespace Tracker.Models
{
    [GridTable(PagingEnabled = true, PageSize = 30)]
    public class INV_Assets 
    {
        // Setting GridColumn Annotations allows you to use AutoGenerateColumns on view to auto create the Grid based on the model.


        public int Id { get; set; }

        public int Model_Id { get; set; }
        [ForeignKey("Model_Id")]
        public virtual INV_Models Model { get; set; }

        [Required]
        public int Manufacturer_Id { get; set; }
        [ForeignKey("Manufacturer_Id")]
        public virtual INV_Manufacturers Manufacturer { get; set; }

        [Required]
        public int Type_Id { get; set; }
        [ForeignKey("Type_Id")]
        public virtual INV_Types Type { get; set; }

        [Required]
        public int Location_Id { get; set; }
        [ForeignKey("Location_Id")]
        public virtual INV_Locations Location { get; set; }

        public int Vendor_Id { get; set; }
        [ForeignKey("Vendor_Id")]
        public virtual INV_Vendors Vendor { get; set; }

        [Required]
        public int Status_Id { get; set; }
        [ForeignKey("Status_Id")]
        public virtual INV_Statuses Status { get; set; }

        public string ip_address { get; set; }

        public string mac_address { get; set; }

        public string note { get; set; }
        public string owner { get; set; }
        public decimal cost { get; set; }
        public string po_number { get; set; }
        public string description { get; set; }

        public int invoice_number{ get; set; }

        [Required]
        public string serial_number { get; set; }

        [Required]
        public string asset_tag_number { get; set; }

        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime? acquired_date { get; set; }

        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime? disposed_date { get; set; }

        [Required]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime created_date { get; set; }

        [Required]
        public string created_by { get; set; }

        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime modified_date { get; set; }

        public string modified_by { get; set; }

        // Flag to specify if item is available? (Not signed out, not auctioned, recycled, etc.)
        //public bool available { get; set; }
    }
}

[INV_Assets] 视图

@using GridMvc.Html
@model  Tracker.Models.INV_Assets

@{
    ViewBag.Title = "Home Page";
}
<table style="width:100%;">

@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.Status)</td>
        <td>@Html.DisplayFor(modelItem => item.Location)</td>
        <td>@Html.DisplayFor(modelItem => item.owner)</td>
        <td>@Html.DisplayFor(modelItem => item.Type)</td>
        <td>@Html.DisplayFor(modelItem => item.Manufacturer)</td>
        <td>@Html.DisplayFor(modelItem => item.Model)</td>
        <td>@Html.DisplayFor(modelItem => item.Vendor)</td>
        <td>@Html.DisplayFor(modelItem => item.description)</td>
        <td>@Html.DisplayFor(modelItem => item.asset_tag_number)</td>
        <td>@Html.DisplayFor(modelItem => item.serial_number)</td>
        <td>@Html.DisplayFor(modelItem => item.ip_address)</td>
        <td>@Html.DisplayFor(modelItem => item.mac_address)</td>
        <td>@Html.DisplayFor(modelItem => item.po_number)</td>
        <td>@Html.DisplayFor(modelItem => item.invoice_number)</td>
        <td>@Html.DisplayFor(modelItem => item.cost)</td>
        <td>@Html.DisplayFor(modelItem => item.note)</td>
        <td>@Html.DisplayFor(modelItem => item.acquired_date)</td>
        <td>@Html.DisplayFor(modelItem => item.disposed_date)</td>
        <td>@Html.DisplayFor(modelItem => item.created_date)</td>
        <td>@Html.DisplayFor(modelItem => item.created_by)</td>
        <td>@Html.DisplayFor(modelItem => item.modified_date)</td>
        <td>@Html.DisplayFor(modelItem => item.modified_by)</td>
    </tr>
}

</table>

我不太确定如何解决这个错误,并想知道是否有更多经验的人可以称重?

我的[INV_Locations] 模型/视图在做同样的事情时没有收到任何问题(不知道为什么):

[INV_Locations]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Tracker.Models
{
    public class INV_Locations
    {
        public int Id { get; set; }
        public string location_dept { get; set; }
        public string location_room { get; set; }

        [Required]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime created_date { get; set; }

        [Required]
        public string created_by { get; set; }

        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime modified_date { get; set; }

        public string modified_by { get; set; }
    }
}

[INV_Locations] 视图

@model IEnumerable<Tracker.Models.INV_Locations>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>Maintenance - Locations</h3>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th></th>
        <th>
            @*@Html.DisplayNameFor(model => model.location_dept)*@
            Dept:
        </th>
        <th>
            Room:
        </th>
        <th>
            Created:
        </th>
        <th>
            By:
        </th>
        <th>
            Modified:
        </th>
        <th>
            By:
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <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>
        <td>
            @Html.DisplayFor(modelItem => item.location_dept)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.location_room)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.created_date)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.created_by)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.modified_date)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.modified_by)
        </td>
    </tr>
}

</table>

我尝试在我的 [INV_Assets] View 上将 @model Tracker.Models.INV_Assets 更改为 @model IEnumerable&lt;Tracker.Models.INV_Assets&gt;(就像我的 [INV_Locations] View 拥有它一样。这允许我的解决方案构建,但是当尝试运行我的应用程序时View 我收到: System.InvalidOperationException The model item passed into the dictionary is of type 'Tracker.Models.INV_Assets', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[Tracker.Models.INV_Assets]'.


编辑 - 关于 Shyju 的建议

我将我的HomeController Index() 更改为:

    TrackerContext _db = new TrackerContext();
    public ActionResult Index(INV_Assets defModel)
    {
        return View(defModel);
    }

到:

    TrackerContext _db = new TrackerContext();
    public ActionResult Index(INV_Assets defModel)
    {
        var assetList = new List<Tracker.Models.INV_Assets>();

        assetList.Add(defModel);
        return View(assetList);
    }

当我的视图现在加载时,我得到的只是表格 HTML:

<table style="width:100%;">

    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td>0</td>
        <td>0.00</td>
        <td></td>
        <td></td>
        <td></td>
        <td>01/01/0001</td>
        <td></td>
        <td>01/01/0001</td>
        <td></td>
    </tr>

</table>

我已确认我的 DBContext 中有 2 条完整的 [INV_Assets] 记录,但它们没有显示在视图中?如何将我的 [INV_Assets] 模型的所有实例正确加载到新的 assetList 变量中?


EDIT2

将我的Index() 修改为:

    TrackerContext _db = new TrackerContext();
    public ActionResult Index(INV_Assets defModel)
    {
        var assetList = _db.INV_Assets.ToList(); // EXCEPTION
        return View(assetList);
    }

但是现在,在构建解决方案时,当我尝试运行应用程序时它会失败。详情如下:

错误An exception of type 'System.Data.DataException' occurred in EntityFramework.dll but was not handled in user code. Additional information: An exception occurred while initializing the database. See the InnerException for details.

留言An exception occurred while initializing the database. See the InnerException for details.

InnerException{"The underlying provider failed on Open."}

来源EntityFramework

【问题讨论】:

    标签: c# asp.net-mvc razor asp.net-mvc-5 ienumerable


    【解决方案1】:

    您的视图绑定到Tracker.Models.INV_Assets 的单个实例。但是在您的视图中,您正试图循环遍历它。您需要确保传递给您的视图的是一个集合,以便我们可以循环遍历它。

    在 INV 资产视图中,更改

    @model Tracker.Models.INV_Assets

    @model  List<Tracker.Models.INV_Assets>
    

    您还需要确保从您的操作方法传递INV_Assets 对象的集合。

    public ActionResult INVAssets()
    {
      var assetList=new List<Tracker.Models.INV_Assets>();
    
      // Ex : manually adding one record. replace with your actual code to load data
      // to do : Add item to the list now
      assetList.Add(new INV_Assets { Name ="Test"});
    
      return View(assetList);     
    }
    

    编辑: 根据问题中的编辑

    您的Index 操作不应将INV_Assets 的对象作为参数。

    TrackerContext _db = new TrackerContext();
    public ActionResult Index()
    {
        var assetList =_db.INV_Assets.ToList();     
        return View(assetList);
    }
    

    假设 INV_Assets 是您的 TrackerContext 类的属性。如果您的属性名称不同,请更改上述代码以反映这一点。

    如果您要加载特定位置的资产,请更新​​您的 Index 操作方法以接受位置 ID 作为参数。

    public ActionResult Index(int id)
    {
        var assetList =_db.INV_Assets.Where(s=>s.Location_Id==id).ToList();     
        return View(assetList);
    }
    

    所以你访问这个页面的网址是这样的

    http://yoursitename/YourControllerName/Index/5
    

    5 是一个有效的位置 ID,其中包含一些与之关联的资产。

    【讨论】:

    • 感谢 Shyju 的回复。当我将您的建议从 IEnumerable&lt;&gt; 更改为 List (添加 using System.Collections.Generic 后)时,我的错误现在变为(类似):System.InvalidOperationException The model item passed into the dictionary is of type 'Tracker.Models.INV_Assets', but this dictionary requires a model item of type 'System.Collections.Generic.List 1[Tracker.Models.INV_Assets]'.
    • 谢谢,我还在想办法把我所有的模型实例加载到新的assetList变量中?
    • 仍然没有任何运气。我在上面添加了一个编辑来显示我在哪里。
    • 我在上面使用您的 ToList() 示例为最新更改发生的新异常创建了一个 EDIT2。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多