接下來講講刪除 部分...
在查詢的View那邊可以看到下方程式碼
@Html.ActionLink("刪除", "Delete", new { categoryID = md.CategoryID }, new { @class = "glyphicon glyphicon-trash"})
註解:如果要傳參數過去Action 可以加上 new { categoryID = md.CategoryID }
進入類別刪除Controller
public ActionResult Delete(string categoryID)
{
try
{
var result = new Category().Delete_Category(categoryID);
if (result)
{
TempData["ResultMessage"] = String.Format("類別[{0}]成功刪除", categoryID);
return RedirectToAction("Index", "Category");
}
else
{ //如果沒有資料則顯示錯誤訊息並導回Index頁面
TempData["ResultMessage"] = "資料有誤,請重新操作";
return RedirectToAction("Index", "Category");
}
}
catch (Exception e)
{
ViewBag.ResultMessage = e.ToString();
return View();
}
}
類別 Model模板
public class Category
{
[Required]
[Display(Name = "類別編號")]
[StringLength(4, ErrorMessage = "{0}的長度至少必須為{2}的字元。", MinimumLength = 1)]
public string CategoryID { get; set; }
[Display(Name = "類別名稱")]
[StringLength(20, ErrorMessage = "{0}的長度至少必須為{2}的字元。", MinimumLength = 1)]
public string CategoryName { get; set; }
public Category()
{
}
public bool Delete_Category(string categoryID)
{
var result = false;
using (var conn = new MySqlConnection(GlobalFunction.GlobalConnString))
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = "Delete From Category Where Category = @Category;
command.Parameters.AddWithValue("@Category", categoryID);
command.ExecuteNonQuery();
result = true;
return result;
}
}
}
}
註解:實務上通常為了資料完整性是不會下Delete語法這點特別注意