前臺使用資料庫model和Html.BeginForm("action", "controller", FormMethod.Post)提交表單,在儲存到資料庫前對錶單項進行判斷的方法(一)
前端:
@model DBEF.XXX
@using (Html.BeginForm("action", "controller", FormMethod.Post))
{
@Html.ValidationSummary(true)
<fieldset style="width: 700px; margin: 0 auto;">
<legend>
新增
</legend>
<div>
<strong>賬號</strong>
</div>
<div>
@Html.EditorFor(model => model.Account, new { @id = "Account" })
<span style="color:red; font-size: small">
@Html.ValidationMessageFor(model => model.Account)
</span>
</div>
<div style="display:none">
@Html.HiddenFor(model => model.Pwd, new { @Value = "" })
</div>
<div>
<strong>姓名</strong>
</div>
<div>
@Html.EditorFor(model => model.Name, new { @id = "Name" })
<span style="color:red; font-size: small">
@Html.ValidationMessageFor(model => model.Name)
</span>
</div>
<div>
<strong>備註</strong>
</div>
<div>
@Html.EditorFor(model => model.Note, new { @id = "Note" })
</div>
<input type="submit" value="新增" id="create" style="margin-right: 20px;" class='bookButton btn btn-success btn-small' />
@Html.ActionLink("取消", "Index", new { }, new { @class = "btn btn-small btn-danger" })
</fieldset>
後端:
public ActionResult action(XXX t)
{
string id = Session["userid"].ToString();
if (string.IsNullOrWhiteSpace(id))
{
return RedirectToAction("Login", "Home");
}
else
{
try
{
var accountFind = db.XXX.Where(m => m.Account == t.Account);
if (accountFind.Count() > 0)
{
//使用者名稱已存在, 此處如何向用戶反饋一個資訊,且View中使用者填的內容不會被清除。
ModelState.AddModelError("Account", "* 該賬號已存在");
return View(t);
}else if (string.IsNullOrWhiteSpace(t.Account))
{
ModelState.AddModelError("Account", "賬號不能為空");
return View(t);
}
else if(string.IsNullOrWhiteSpace(t.Name))
{
ModelState.AddModelError("Name", "姓名不能為空");
return View(t);
}
if (ModelState.IsValid)
{
db.XXX.Add(t);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View(t);
}
}
}