我们将在文章列表页(Index.cshtml
)中添加一个搜索框,并根据用户输入的关键词动态过滤文章。
Pages/Posts/Index.cshtml.cs
添加搜索字段和逻辑:
[BindProperty(SupportsGet = true)]
public string? SearchTerm { get; set; }
public async Task<IActionResult> OnGetAsync()
{
var query = _context.Posts
.Include(p => p.Category)
.Include(p => p.PostTags).ThenInclude(t => t.Tag)
.AsQueryable();
if (CategoryId.HasValue)
{
query = query.Where(p => p.CategoryId == CategoryId.Value);
}
if (!string.IsNullOrEmpty(SearchTerm))
{
query = query.Where(p =>
p.Title.Contains(SearchTerm) ||
p.Content.Contains(SearchTerm) ||
p.AuthorName.Contains(SearchTerm));
}
Posts = await query.ToListAsync();
Categories = await _context.Categories.ToListAsync();
return Page();
}
Pages/Posts/Index.cshtml
在页面顶部添加搜索框:
<form method="get">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="搜索文章..." asp-for="SearchTerm" />
<button class="btn btn-outline-primary" type="submit">搜索button>
div>
form>
你也可以将它放在导航栏或侧边栏中,方便用户随时搜索。
如果你希望提升搜索性能,可以考虑启用 SQL Server 的全文搜索功能。
在 SQL Server 中启用全文搜索:
EXEC sp_fulltext_database 'enable';
创建全文索引:
CREATE FULLTEXT INDEX ON Posts(Title, Content)
KEY INDEX PK_Posts_Id
ON BlogCatalog;
修改 LINQ 查询为使用 EF.Functions.FreeSql
或直接调用 SQL 函数(需使用原生 SQL 查询)。
⚠️ 注意:这属于高级用法,适用于数据量较大时。对于小型博客系统,简单的
Contains()
已经足够。
git add .
git commit -m "Day6: Added search functionality by title, content and author"
今天你完成了:
✅ 实现了按标题、内容、作者搜索文章的功能
✅ 使用 LINQ 构建动态查询逻辑
✅ 添加了搜索框 UI 界面
✅ 可选学习了 SQL Server 全文搜索配置
✅ 提交版本控制记录
我们将进入 测试与优化阶段: