新增文章已經做完了,今天就來做撈出文章列表的功能,這樣才能看到新增的成果。
我們今天會把查詢文章做在,一進去的首頁,所以放在HomeController 裡面,因為正常來說一進到首頁就看到文章是合理的。
目標:
1.查詢文章介面、實做
2.HomeController 注入Article 介面
3.做View 頁面
步驟:
step1.IArticleService.cs
Task<IList<Article>> GetArticle(long? id);
step2.ArticleService.cs
public async Task<IList<Article>> GetArticle(long? id)
{
if (id == null)
{
return await _db.Articles
.Where(x => x.IsDelete == false)
.OrderByDescending(x => x.Id)
.Take(1)
.ToListAsync();
}
else
{
return await _db.Articles
.Where(x => x.IsDelete == false && x.Id == id)
.OrderByDescending(x => x.Id)
.ToListAsync();
}
}
step3. HomeController 改寫成這樣 (這邊很單純,就是取值出來後往View送)
public async Task<IActionResult> Index()
{
var model = await _article.GetArticle(null);
var result = new List<ArticleViewModel>();
if (model is not null && model.Count > 0)
{
result = model.Select(x => new ArticleViewModel
{
Id = x.Id,
ArticleContent = x.ArticleContent,
Title = x.Title
}).ToList();
TempData["ArticleLastId"] = result.Last().Id.ToString();
}
return View(result);
}
step4. 在 Viewmodel 資料夾裡面新增此物件(用來傳直到View 裡面的物件)
public class ArticleViewModel
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string ArticleContent { get; set; } = string.Empty;
}
step5. 新增首頁畫面
@model IEnumerable<ArticleViewModel>;
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center mb-2">
<h1 class="display-4">Welcome</h1>
</div>
<hr/>
@if (Model != null && Model.Count() > 0)
{
<div id="articleIndex" class="text-center mt-5">
@foreach (var item in Model)
{
<h3 class="display-4">
<a href="~/Article/@item.Id">@item.Title</a>
</h3>
}
</div>
}
這樣成功執行起來的話,應該就可以看到首頁有資料囉~