【MVC】.NET實踐(四)—新增資料到資料庫
阿新 • • 發佈:2018-12-18
1、在主介面Index.cshtml新增“新增”的連結
<tr>
<td colspan="4"> @Html.ActionLink("新增", "Add", "Home") @Html.ActionLink("返回", "Index", "Home")</td>
</tr>
2、HomeController
2.1顯示新增
[HttpGet]
public ActionResult Add()
{
return View();
}
2.2執行新增
[HttpPost] public ActionResult Add1() { try { //DbEntityEntry<BlogUser> entry = db.Entry<BlogUser>(blogUser); BlogUser user = new BlogUser(); user.Id = int.Parse(Request["id"]); user.Name = Request["name"]; user.State =bool.Parse(Request["state"]); ViewData.Model = user; //db.BlogUser.Attach(user); db.BlogUser.Add(user); db.SaveChanges(); return RedirectToAction("Index", "Home"); } catch (Exception ex) { return Content("新增失敗," + ex.Message); } }
3、Add.cshtml
@using (Html.BeginForm("Add1", "Home", FormMethod.Post)) { <table id="tbList"> <tr> <td colspan="2">新增</td> </tr> <tr> <td>賬號:</td> <td><input type="text" id="id" name="id" /></td> </tr> <tr> <td>姓名:</td> <td><input type="text" id="name" name="name" /></td> </tr> <tr> <td>狀態:</td> <td><input type="text" id="state" name="state" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="確認新增" />@Html.ActionLink("返回", "Index", "Home")</td> </tr> </table> }
其中name很關鍵,在controller中通過name來用request獲取輸入的值
佈局程式碼
<title>新增</title> <style type="text/css"> #tbList { border: 1px solid #0094ff; width: 400px; margin: 10px auto; border-collapse: collapse; } #tbList th, td { border: 1px solid #0094ff; padding: 10px; } </style>