【问题标题】:Pass Model to View using IEnumerable type使用 IEnumerable 类型将模型传递给视图
【发布时间】:2014-09-28 15:57:25
【问题描述】:

我想从数据库中获取发票项目,但是IEnumerable Type有问题

错误
传入字典的模型项的类型为“System.Data.Entity.DynamicProxies.InvoiceHD_19624A0A21E23E6589B4A75F4B214A34A6186F3A2FF588A6B9CC2A40272A9BBD”,但此字典需要“System.Collections.Generic.IEnumerable`1[ICSNew.Data.InvoiceHD] 类型的模型项

我的控制器

public ActionResult GetInvoice(int Id)
{
    Models.InvoiceHDViewModel _invHd = new Models.InvoiceHDViewModel();

    ICSNew.Data.InvoiceHD _invOdr = new Data.InvoiceHD();
    _invOdr = (new ICSNew.Business.ICSNewController.SalesController())
                  .GetInvoiceItemByInvoiceId(Id);
    _invHd.Cash = _invOdr.CashAmount;

    return View(_invOdr);
}

我的观点

@model IEnumerable<ICSNew.Data.InvoiceHD>

@{
    Layout = null;
}

<h2>GetInvoice</h2>

@foreach (var item in Model)
{
    @Html.DisplayFor(modelItem => item.CashAmount)
}

我的仓库

public InvoiceHD GetInvoiceItemByInvoiceId(int InvoiceId)
{
    try
    {
        return context.InvoiceHDs.Where(x => x.InvoiceId == InvoiceId 
            && x.IsActive == true).FirstOrDefault();
    }
    catch (Exception ex)
    {
        return new InvoiceHD();
    }
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    由于您将InvoiceHD 的实例传递给视图,因此您需要将模型更改为InvoiceHD 并删除视图代码中的foreach 块,如下所示

    @model ICSNew.Data.InvoiceHD
    
    @{
        Layout = null;
    }
    
    <h2>GetInvoice</h2>
    
    @Html.DisplayFor(m => m.CashAmount)
    

    【讨论】:

      【解决方案2】:

      正如错误试图告诉您的那样,您将视图声明为采用对象的集合 (IEnumerable&lt;&gt;),但您尝试将单个对象实例传递给它。

      那行不通。

      【讨论】:

      • 在我的 Irepository > InvoiceHD GetInvoiceItemByInvoiceId(int InvoiceId);
      • @TechGuy:然后呢?你明白这个问题了吗?
      • 当我在视图中删除 IEnumerable 时,它​​显示错误 > foreach 语句无法对“ICSNew.Data.InvoiceHD”类型的变量进行操作,因为“ICSNew.Data.InvoiceHD”不包含'GetEnumerator'
      • 我认为它说不是集合和/或不可枚举类型
      • 没错。你为什么要循环处理一件事情?
      猜你喜欢
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 2019-04-01
      • 2011-02-20
      • 1970-01-01
      相关资源
      最近更新 更多