这是我的控制器:
public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
ViewData["CurrentSort"] = sortOrder;
ViewData["GenreSortParm"] = string.IsNullOrEmpty(sortOrder) ? "genre_desc" : "";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
ViewData["CurrentFilter"] = searchString;
var userBooks = _userService.PagedUserBooks(user, sortOrder, currentFilter, searchString, page);
var result = await PaginatedList<Book>.CreateAsync(userBooks, page ?? 1, 5);
return View(result);
}
“ userBooks”是一个IQueryable,因此可以在“ CreateAsync”中传递它,而我传递给View的“结果”是PaginatedList
在我的视图中,我正在使用@model PaginatedList<Book>
,这是我的视图这一部分的问题
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@item.Genre
</td>
<td>
@item.Title
</td>
<td>
@item.CreatedOn
</td>
<td>
<a asp-controller="Book" asp-action="MakeReview" asp-route-id="@item.Id" class="btn btn-success">Add Review</a>
</td>
</tr>
}
</tbody>
我使用asp-route-id="@item.Id"
,它是项目的ID,即Book,因此我可以将ID传递给<a asp-controller="Book" asp-action="MakeReview" asp-route-id="@item.Id" class="btn btn-success">Add Review</a>
中指定的操作“ MakeReview”
但是当我使用动作方法
[HttpGet]
public async Task<IActionResult> MakeReview(int bookId)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
var book = await _bookService.GetById(user, bookId);
//Not fully implemented
return View();
}
作为参数传递的int bookId应该是我选择查看的书的ID,但始终为0。这与将PaginatedList用作模型有关,而在类中我没有Id的属性?这是我的课程“ PaginatedList”
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}
更新: 当操作MakeReview中的参数类型为Book而不是int类型,并且我将int的ID传递给Action时,则模型绑定工作了,当然,除了ID之外,所有内容都为空。