asp.net核心传递linq lambda来查看

时间:2016-07-28 12:04:22

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

我正在使用asp.net core,当我通过linq lambda query查看时出现此错误:

An unhandled exception occurred while processing the request.

InvalidOperationException: The model item passed into 
the ViewDataDictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType7`1[System.Int64]]',
but this ViewDataDictionary instance 
requires a model item of type 'System.Collections.Generic.IEnumerable`1[HRMS.Salaries]'.

我的查询:

public async Task<IActionResult> Index()
{
  var salary = (from salaries in _context.Salaries select new { salaries.Id });
  return View(await salary.ToListAsync());
}

在我使用的视图中:

@model IEnumerable<HRMS.Salaries>

  @foreach (var item in Model)
  {
    <tr>
       <td>@item.Id</td> 
    </tr>
  } 

1 个答案:

答案 0 :(得分:0)

您是否有理由在查询中创建对象?如果不是,请尝试这样做:

public async Task<IActionResult> Index()
        {
            var salary = (from salaries in _context.Salaries
                          select salaries.Id
                      );
            return View(await salary.ToListAsync());
        }

然后在你看来:

@model IEnumerable<int>

                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>@item</td> 
                        </tr>
                    } 

否则,如果您需要该对象,请在查询中使用:

public async Task<IActionResult> Index()
            {
                var salary = (from salaries in _context.Salaries
                              select salaries
                          );
                return View(await salary.ToListAsync());
            }

保持观点一致:

@model IEnumerable<HRMS.Salaries>

                        @foreach (var item in Model)
                        {
                            <tr>
                                <td>@item.Id</td> 
                            </tr>
                        } 

编辑:如果要将多个字段传递给View,最好使用新对象。为此,使用必填字段创建一个类(例如, SalaryDetailsViewModel )。然后在你的控制器中:

public async Task<IActionResult> Index()
        {
            var salary = (from salaries in _context.Salaries
                          select new SalaryDetailsViewModel { 
                              Id = salaries.Id,
                              Amount = salaries.Amount,
                              Date = salaries.Date,
                              JobTitle = salaries.JobTitle.Name }
                      );
            return View(await salary.ToListAsync());
        }

然后调整视图以调用自定义对象的不同字段,以用于显示目的,例如:

@model IEnumerable<SalaryDetailsViewModel>

                        @foreach (var item in Model)
                        {
                            <tr>
                                <td>@item.Id</td>
                                <td>@item.Amount</td>
                                <td>@item.Date</td>
                                <td>@item.JobTitle</td>
                            </tr>
                        }