gpt4 book ai didi

asp.net-core-mvc - 如何在 MVC CORE 中对 ViewModel 进行分页?

转载 作者:行者123 更新时间:2023-12-03 15:47:23 25 4
gpt4 key购买 nike

在来自 https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page 的 MVC 核心演示中Contoso 大学示例程序在分页示例页面上使用模型

var students = from s in _context.Students
select s;
return View(await PaginatedList<Student>.CreateAsync(students.AsNoTracking(), page ?? 1, pageSize));

当 View 模型像这样作为一个完整的实体传回时

var viewModel = new InstructorIndexData();
viewModel.Instructors = await _context.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.CourseAssignments)
.ThenInclude(i => i.Course)
.ThenInclude(i => i.Department)
.OrderBy(i => i.LastName)
.ToListAsync();

return View(viewModel);

如何对 View 模型的返回记录进行分页。

我试过像这样将 View 模型传递到 PaginatedList。

return View(await PaginatedList<InstructorIndexData>.CreateAsync(viewModel.AsNoTracking(), page ?? 1, pageSize));

有错误

Error   CS1061  'InstructorIndexData' does not contain a definition for 'AsNoTracking' and no extension method 'AsNoTracking' accepting a first argument of type 'InstructorIndexData' could be found (are you missing a using directive or an assembly reference?) 

编辑 View 模型是

namespace ContosoUniversity.Models.SchoolViewModels
{
public class InstructorIndexData
{
public IEnumerable<Instructor> Instructors { get; set; }
public IEnumerable<Course> Courses { get; set; }
public IEnumerable<Enrollment> Enrollments { get; set; }
}
}

将 IEnumerable 更改为 IQueryable 会导致以下情况

    var viewModel = new InstructorIndexData();
viewModel.Instructors = await _context.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.CourseAssignments)
.ThenInclude(i => i.Course)
.ThenInclude(i => i.Department)
.OrderBy(i => i.LastName)
.ToListAsync();

产生错误

Cannot implicitly convert type 'System.Collections.Generic.List<ContosoUniversity.Models.Instructor>' to 'System.Linq.IQueryable<ContosoUniversity.Models.Instructor>'. An explicit conversion exists (are you missing a cast?)

最佳答案

AsNoTracking()

是在 DbExtension 程序集中定义的扩展方法。属性“Instructors”必须是实现“IQueryable”的类型才能启用此扩展方法。

此外,在您提供的代码示例中

return View(await PaginatedList<InstructorIndexData>.CreateAsync(viewModel.AsNoTracking(), page ?? 1, pageSize));

您正在对 viewModel 本身使用扩展方法,而不是属性“Instructors”

关于asp.net-core-mvc - 如何在 MVC CORE 中对 ViewModel 进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45413078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com