(入門文章)MVC實作CRUD-Create
繼上一章MVC使用CodeFirst技術實現基礎連結資料庫後,
接下來可再深入一點對資料庫作CRUD
繼承上一章的Model已經決定了,那就剩下Controller與View部分了
1.先處理Create功能的Controller部分與View部分
(1)於HomeController新增Create動作部分程式碼如下
//導到Create頁面
//[HttpGet]
public ActionResult Create()
{
return View();
}
//Create表單提交
[HttpPost]
public ActionResult Create(GuestBookEntity GuestBookEntity)
{
//將資料寫進DB
if (ModelState.IsValid)
{
mo.MyEntities.Add(GuestBookEntity);
mo.SaveChanges();
return RedirectToAction("Index");//導回Index Redirection(Index)
}
return View(GuestBookEntity);
}
主要實作導到Create頁面與表單實作
(2)新增Create View頁面
滑鼠按右鍵「新增檢視」選項加入Creae範本,設定如下
加入View完成後,Create功能也就完成了
2.不過我想要了解剛所新增的View裡面有幾個值得記住的項目
@model MyGuestBook2.Models.GuestBookEntity
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>GuestBookEntity</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Message, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
(1)傳給View的model預設是GuestBookEntity(Table)
(2)使用@Html.LabelFor方法相當於產生<label>標籤
(3)使用@Html.EditorFor方法相當於產生<input>標籤