接下来讲讲 Model 验证规则部分...
在 模型类别上方需加入
using System.ComponentModel.DataAnnotations;
内建验证属性如下
类别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)]
}
类别Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Category postback)
{
try
{
if (this.ModelState.IsValid)
{
if (!new Category().IsCategoryidExist(postback.CategoryID))
{
ViewBag.ResultMessage = "类别编号已存在";
return View(postback);
}
else
{
var result = new Category().Post_Category(postback, Type, (string)Session["UserID"]);
if (result)
{
TempData["ResultMessage"] = String.Format("类别[{0}]成功新增", postback.CategoryID);
return RedirectToAction("Index", "Category");
}
else
{
ViewBag.ResultMessage = "资料有误,请检查";
return View(postback);
}
}
}
else
{
ViewBag.ResultMessage = "资料有误,请检查";
return View(postback);
}
}
catch (Exception e)
{
ViewBag.ResultMessage = e.ToString();
return View();
}
}
注解:this.ModelState.IsValid 就会进入类别Model 的验证判断
类别View
@model WebApplication1.Models.Category.Category
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
@using (Html.BeginForm("Create", "Category", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>类别资料新增作业</h2>
<hr />
@if (ViewBag.ResultMessage != null)//判断如果有讯息,则显示。
{
<script type="text/javascript">
var message = @Html.Raw(Json.Encode(ViewBag.ResultMessage));
alert(message);
</script>
}
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.CategoryID, htmlAttributes: new { @class = "control-label col-md-1" })
<div class="col-md-10">
@Html.EditorFor(model => model.CategoryID, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CategoryName, htmlAttributes: new { @class = "control-label col-md-1" })
<div class="col-md-10">
@Html.EditorFor(model => model.CategoryName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CategoryName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="存档" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("返回清单", "Index")
</div>
注解: @Html.ValidationMessageFor 则会显示类别Model的ErrorMessage 讯息,@Html.ValidationSummary则是会显示所有验证失败的讯息
<<: Day 18. 计算属性(Computed) VS 侦听属性(Watched Property)
看到这篇觉得满实用的,来跟着看一下。 连结: https://www.protopie.io/blo...
链表算是常出的题型之一吧(? 今天先整理出相对直观好理解的题目,明天补上比较需要思考的 链表也不需要...
Synology 虽然提供很方便的 QuickConnect 可让用户端应用程序透过网际网路连线至 ...
在上一篇:用HTML、CSS、JS打造个人网站 (2),完成了网页的所有内容,接下来的工作就是让网...
这里空置了两个礼拜多,总之我要延毕了,怎麽说呢,大家都说延毕不是世界末日,我现在也接受这个说法了,不...