ASP.NET MVC 从入门到放弃(Day25)-MVC模型验证介绍

接下来讲讲 Model 验证规则部分...

在 模型类别上方需加入

using System.ComponentModel.DataAnnotations;

内建验证属性如下


  • [ValidateNever]: ValidateNeverAttribute 指出属性或参数应该从验证中排除。
  • [CreditCard]:验证属性是否具有信用卡格式。 需要 JQuery 验证的其他方法。
  • [Compare]:验证模型中的两个属性是否相符。
  • [EmailAddress]:验证属性具有电子邮件格式。
  • [Phone]:验证属性具有电话号码格式。
  • [Range]:验证属性值是否落在指定的范围内。
  • [RegularExpression]:验证属性值是否符合指定的正则运算式。
  • [Required]:验证栏位不是 null。 如需此属性行为的详细资讯,请参阅 [Required] 属性。
  • [StringLength]:验证字串属性值不超过指定的长度限制。
  • [Url]:验证属性是否具有 URL 格式。
  • [Remote]:在服务器上呼叫动作方法,以验证用户端上的输入。 如需此属性行为的详细资讯,请参阅 [Remote] 属性。
  • [DataType(DataType.MultilineText]:多列文字
  • [HiddenInput(DisplayValue = false)]:隐藏输入
  • [DataType(DataType.DateTime)]:属性是时间

类别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则是会显示所有验证失败的讯息

参考资料MSDN


<<:  Day 18. 计算属性(Computed) VS 侦听属性(Watched Property)

>>:  铁人赛 Day30 -- 铁人赛最後一天啦

连续 30 天 玩玩看 ProtoPie - Day 25

看到这篇觉得满实用的,来跟着看一下。 连结: https://www.protopie.io/blo...

DAY5 - 链表(一)

链表算是常出的题型之一吧(? 今天先整理出相对直观好理解的题目,明天补上比较需要思考的 链表也不需要...

设定固定 IP + DDNS

Synology 虽然提供很方便的 QuickConnect 可让用户端应用程序透过网际网路连线至 ...

[Day 16 - 小试身手] 用HTML、CSS、JS打造个人网站 (3)

在上一篇:用HTML、CSS、JS打造个人网站 (2),完成了网页的所有内容,接下来的工作就是让网...

Leetcode: 226. Invert Binary Tree

这里空置了两个礼拜多,总之我要延毕了,怎麽说呢,大家都说延毕不是世界末日,我现在也接受这个说法了,不...