我已经尝试了一段时间,试图弄清楚如何成功地判断我的搜索是否成功。我应该在搜索失败时登录,也就是在列表中找不到任何内容时登录。我认为这与尝试/捕获解决方案有关。如果这是一个非常愚蠢的问题,我很抱歉,但我一直在四处寻找,如果搜索结果没有数据,我似乎找不到办法。下面的代码是我用来搜索整个分页列表的代码。
public async Task<IActionResult> Index(string sortorder, int pageNumber = 1, string searchString = "", string searchString2 = "", string searchString3 = "")
{
var game = from g in _context.Cheats
select g;
ViewData["PlatformSortParam"] = String.IsNullOrEmpty(sortorder) ? "platform_sort" : "";//default sort
ViewData["CurrentFilter"] = searchString;
ViewData["CurrentFilter2"] = searchString2;
ViewData["CurrentFilter3"] = searchString3;
if (!String.IsNullOrEmpty(searchString))
{
game = game.Where(b => b.Game.Contains(searchString));
try
{
}
catch(Exception ex)
{
}
_logger.Log(LogLevel.Warning, (EventId)404, "Search string failed while trying to search for {searchString}", searchString);
}
if (!String.IsNullOrEmpty(searchString2))
{
game = game.Where(b => b.CheatName.Contains(searchString2));
}
if (!String.IsNullOrEmpty(searchString3))
{
game = game.Where(b => b.Platform.Contains(searchString3));
}
return View(await PaginatedList<Cheats>.CreateAsync(game, pageNumber, 10));
//return View(await PaginatedList<Cheats>.CreateAsync(_context.Cheats, pageNumber, 10));
}
这是PaginatedList类的代码。
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; 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 PreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool NextPage
{
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);
}
}
我使用是为了记录它。不知道如何使用try/catch,但这对我的解决方案有效。
if (game.Count() == 0)
{
_logger.Log(LogLevel.Warning, (EventId)404, "Search string failed while trying to search for {searchString}", searchString);
}