我希望在ASP.NET Core2.2中使用ViewModel
分页。
您可以在下面看到我的代码
public class UserQuestionListComplexViewModel { //There are 2 ViewModel in this Class public UserPanelViewModel Model1 { get; set; } public List<UserQuestionListViewModel> Model2 { get; set; } }
在我的控制器里
public class UserHomeController : Controller { private readonly UserManager<ApplicationUsers> _userManager; private readonly IQuestionRepository _iq; public UserHomeController(UserManager<ApplicationUsers> userManager, IQuestionRepository iq) { _userManager = userManager; _iq = iq; } [HttpGet] public async Task<IActionResult> QuestionList(UserQuestionListComplexViewModel model, int page = 1) { var query = _iq.UserQuestionList(_userManager.GetUserId(HttpContext.User), page); model.UQVM = await query; return View(model); } }
下面是问题库
public async Task<List<UserQuestionListViewModel>> UserQuestionList(string UserID, int page = 1) { var questionQuery = (from q in _db.QuestionTbl where q.UserID == UserID select new UserQuestionListViewModel() { .... }) .AsNoTracking() .Where(q => q.qflag == 0) .OrderBy(q => q.QuestionID); var pagedResult = await PagingList<UserQuestionListViewModel>.CreateAsync( questionQuery, 1, page); return pagedResult; }
在结尾处view.cshtml
@model UserQuestionListComplexViewModel
@using ReflectionIT.Mvc.Paging
@await Component.InvokeAsync("UserInfo", Model.Model1)
<div>
<table>
<thead class="thead-dark">
<tr>
<td>...</td>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Model2)
{
<tr>
<td>...</td>
</tr>
}
</tbody>
</table>
<nav class="pagenav">
@await this.Component.InvokeAsync("Pager", new { PagingList = this.Model })
</nav>
</div>
但我得到以下错误
InvalidOperationException:传递到ViewDataDidictionary得模型项类型为“reflectionit.mvc.Paging.PagingList”1[Porseman.Models.ViewModels.UserQuestionListViewModel]“,但此ViewDataDidictionary实例需要类型为”Porseman.areas.UserPanel.Models.UserComplexViewModel.UserQuestionListComplexViewModel“得模型项。
查看您的PagingList
创建函数,类型为UserQuestionListViewModel
:
var pagedResult = await PagingList<UserQuestionListViewModel>.CreateAsync(questionQuery, 1, page);
但是当您在视图中配置PagingList
时,您正在设置类型UserQuestionListComplexViewModel
,因此请替换此行:
@await this.Component.InvokeAsync("Pager", new { PagingList = this.Model })
与:
@await this.Component.InvokeAsync("Pager", new { PagingList = this.Model.Model2 })
此外,您可能需要将视图模型中的model2
类型更改为PagingList<;UserQuestionListViewModel>
:
public PagingList<UserQuestionListViewModel> Model2 { get; set; }