【问题标题】:Query Display Error查询显示错误
【发布时间】:2019-01-23 17:05:38
【问题描述】:

我在安装和显示此查询时遇到错误。

var itens = _context.ContasReceber
  .Include(x => x.Pessoas)
  .Include(x => x.PlanosServicos)
  .Select(c => new
  {
     Identificador = c.Pessoas.NIdentificador,
     NomePessoa = c.Pessoas.Nome,
     c.Observacao,
     c.Vencimento,
     c.Valor,
     c.Quitado,
     c.DataPagamento,
     c.ValorPago
    })
    .ToList();
    ViewData["Contas"] = itens;

cshtml:

@foreach (var item in ViewBag.Contas)
 {
    <tr>
      <th>
          @item.Identificador              
      </th>
       <th>
          @item.NomePessoa
       </th>
       <th>
          @item.Observacao
        </th>
        <th>
          @item.Vencimento
        </th>
        <th>
          @item.Quitado
        </th>
         <th>
          @item.DataPagamento
         </th>
         <th>
            @item.ValorPago
         </th>
     </tr>
}

错误是:

处理请求时发生未处理的异常。 RuntimeBinderException:“object”不包含“Identificador”的定义 CallSite.Target(Closure , CallSite , object )

【问题讨论】:

  • 您遇到了this 问题。一个常见的解决方案是创建一个“ViewModel”,它具有您要在该特定视图中使用的属性,并将您的实体属性投影到其中。 AutoMapper 非常适合这个。

标签: asp.net entity-framework asp.net-core


【解决方案1】:

在 razor pages PageModel 中,您可以使用 ViewModel 返回自定义数据。 这是演示的简化版本。

在cshtml.cs中:

 public class ContasViewModel
    {
        public string Identificador { get; set; }
        public string NomePessoa { get; set; }
        public string Observacao { get; set; }
    }

    public IList<ContasViewModel> Contas { get; set; }

    public async Task OnGetAsync()
    {

        Contas = await _context.ContasReceber
          .Include(x => x.Pessoas)
          .Include(x => x.PlanosServicos)
          .Select(c => new ContasViewModel
          {
              Identificador = c.Pessoas.NIdentificador,
              NomePessoa = c.Pessoas.Nome,
              Observacao= c.Observacao

          }).ToListAsync();

    }

在cshtml中:

 @foreach (var item in Model.Contas)
    {
        <tr>
            <th>
                @item.Identificador
            </th>
            <th>
                @item.NomePessoa
            </th>
            <th>
                @item.Observacao
            </th>

        </tr>
    }

【讨论】:

    【解决方案2】:

    当迭代您的项目 foreach (var item in ViewBag.Contas) 时,item 的类型是 Object。默认情况下,对象没有属性。由于您使用的是匿名类型,因此您可以将 foreach 更改为 foreach (dynamic item in ViewBag.Contas),这将允许您引用其属性,因为它将 item 视为类似于 ViewBag 的动态对象。

    【讨论】:

    • 连续收到同样的错误:处理请求时出现未处理的异常。 RuntimeBinderException:“object”不包含“Identificador”CallSite.Target(Closure,CallSite,object)的定义
    • 其实它不是一个控制器,它是一个来自asp.net razor的“PageModel”。在这种情况下,“ViewBag”元素无法识别。
    猜你喜欢
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多