ASP.NET MVC入門教程(六)文章的管理
本部分內容主要包括
1.文章的編輯:文章的編輯部分前端視圖與發表文章的視圖基本一致
2.文章的刪除
一、文章的編輯
1.創建文章的編輯視圖
在Article控制器的Edit(int id)方法內右鍵單擊,選擇添加視圖
將Create視圖的代碼複製到Eidt視圖中。
2.在Edit(int id)方法中輸入以下代碼。
對於編輯,要先根據其id取得文章的內容,並在視圖上進行呈現,以便於用戶進行內容的修改.在操作之前,先修改一下ArticleCreateViewModel視圖模型,爲其加上id屬性。如果我們編輯也使用該視圖模型,就必須有Id,否則,我們在更新記錄時,要用到其Id。如果不想修改該模型,就重新另建一個視圖模型即可。
public int id { get; set; }
[Display(Name ="文章標題")]
[Required(ErrorMessage ="文章標題不能爲空")]
[MinLength(6,ErrorMessage ="文章標題不能少於6個字符")]
[MaxLength(30,ErrorMessage ="文章標題不能超過30個字符")]
public string title { get; set; }
// GET: Article/Edit/5
public ActionResult Edit(int id)
{
tb_article tArticle = db.tb_article.Find(id);
ArticleCreateViewModel article = new ArticleCreateViewModel();
article.id = id;
article.title = tArticle.Name;
article.author = tArticle.Author;
article.content = tArticle.Content;
return View(article);
}
3.測試是否以在視圖上顯示數據,首先打開列表頁(Index),從列表頁點擊編輯文章,以打開編輯文章視圖頁。
4.編寫[HttpPost]的Edit方法
// POST: Article/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Edit(ArticleCreateViewModel article)
{
if (ModelState.IsValid)
{
tb_article tArticle = db.tb_article.Find(article.id);
tArticle.Name = article.title;
tArticle.Author = article.author;
tArticle.Content = article.content;
db.Entry(tArticle).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(article);
}
二、文章的刪除
1.修改文章列表頁
刪除文章時,直接在文章列表頁點擊“刪除文章”,應該彈出對話框,詢問用戶是否確定刪除,如果確定刪除,則刪除,否則,什麼也不做。
<td>
@Html.ActionLink("編輯文章", "Edit", new { id=item.id }) |
@Html.ActionLink("文章內容", "Details", new { id=item.id }) |
@Html.ActionLink("刪除文章", "Delete", new { id=item.id }, new { @onclick = "return confirm('確定要刪除此記錄嗎?')" })
</td>
new { @onclick = "return confirm('確定要刪除此記錄嗎?')" }用於彈出詢問對話框,詢問用戶是否確定刪除文章
2.編寫刪除文章業務代碼
刪除Delete(int id)方法。在下面的的Delete方法中輸入以下代碼
[HttpPost]
public ActionResult Delete(int id)
{
tb_article article = db.tb_article.Find(id);
db.tb_article.Remove(article);
db.SaveChanges();
return RedirectToAction("Index");
}
三、測試文章的刪除