先建立頁面
取名叫 create.cshtml
程式碼如下
@using System.Web.Mvc;
@model MVC30dayAdoNet.Models.Employee
@{
ViewBag.Title = "新增員工";
}
<h2>新增員工</h2>
@using (Html.BeginForm("Create", "Employee", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-group">
帳號
@Html.EditorFor(model => model.LoginID, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LoginID, "", new { @class = "text-danger" })
</div>
<div class="form-group">
姓名
@Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
<div class="form-group">
性別
<div>
@Html.RadioButtonFor(model => model.Gender, "M", new { id = "genderMale" }) 男
@Html.RadioButtonFor(model => model.Gender, "F", new { id = "genderFemale" }) 女
</div>
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
</div>
<div class="form-group">
電話
@Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<input type="submit" value="新增" class="btn btn-primary" />
</div>
}
<div>
@Html.ActionLink("返回", "Index")
</div>
Controller 建立兩個方法
第一個如下
public ActionResult Create()
{
return View();
}
第二個方法如下
[ValidateAntiForgeryToken]
public ActionResult Create(Employee Employee)
{
int count = 0;
if (ModelState.IsValid)
{
string sql = $"Insert Into Employee ([LoginID],[username],[gender],[phone_number]) Values('{Employee.LoginID}','{Employee.Username}','{Employee.Gender}','{Employee.PhoneNumber }')";
DBHelper db = new DBHelper();
count = db.ExecuteNonQuery(sql);
}
if (count > 0)
{
return RedirectToAction("Index");
}
return View(Employee);
}
程式重點說明如下
[ValidateAntiForgeryToken]:這是一個屬性,
用於防止跨網站請求偽造(Cross-Site Request Forgery,CSRF)攻擊。確保請求是從合法發送的。
public ActionResult Create(Employee Employee):這是控制器的操作方法,它處理用戶提交的表單數據。Employee 參數表示從前端表單提交的數據。
return RedirectToAction("Index");:如果新增操作成功,將用戶重定向到 Index ,顯示列表的頁面。
return View(Employee);:如果新增操作失敗,將返回到包含表單的 Create Views。
執行畫面如下
顯示新增畫面