.NET Core第28天_ValidationMessageTagHelper和ValidationSummaryTagHelper的使用

在.net core MVC当中针对model验证是有支援双重验证的机制,也就是在Client端跟Server端都作验证。
微软对於model validation 有专门封装验证标签帮助程序,分两种:
1.验证讯息标签协助程序(ValidationMessageTagHelper):针对单个输入标签协助程序进行验证,是在<span>上做警示显示的,使用asp-validation-for属性实践ViewModel中property的验证。

2.验证摘要标签协助程序(ValidationSummaryTagHelper):针对整个页面上的输入标签协助程序进行验证,是在<div>上做警示显示的。
使用asp-validation-summary属性来设置如下三种固定不同情况的检视模型验证机制:
(1) All:显示的验证资讯是属型和模型的层级。
(2) ModelOnly:显示的验证资讯仅仅是属於模型的层级。
(3) None:不显示验证资讯。

ValidationMessageTagHelper

Client-Side验证

新建ValidationMessageController.cs跟相应Index检视
Index.cshtml

@model ValidationMessageViewModel
<form>
    <div>
        <label asp-for="Name"></label>
        <input type="text" asp-for="Name" />
        <span asp-validation-for="Name"></span>
    </div>
    <div>
        <label asp-for="Age"></label>
        <input type="text" asp-for="Age" />
        <span asp-validation-for="Age"></span>
    </div>
    <div>
        <input type="submit" value="提交" />
    </div>
</form>

跟ValidationMessageViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Net5App6.Models
{
    public class ValidationMessageViewModel
    {
        [Display(Name="姓名")]
        [Required(ErrorMessage ="{0}不可为空!")]
        public string Name { get; set; }

        [Display(Name="年龄")]
        [Required(ErrorMessage ="{0}不可为空")]
        [Range(18,65)]
        public int Age { get; set; }
    }
}

当运行要执行验证的功能按提交按钮是没有反应的
原因在於没有引入验证相关的js脚本

预设专案创建完
在./Views/Shared/_ValidationScriptsPartial.cshtml 此部分检视当中有进行
jquery和验证相关的脚本
https://ithelp.ithome.com.tw/upload/images/20210928/20107452WmToXhVlwI.png

在主要的布局检视
./Views/Shared/_Layout.cshtml
有使用到此语法,第二个参数为false代表可加可不加。
@await RenderSectionAsync("Scripts", required: false)

https://ithelp.ithome.com.tw/upload/images/20210928/201074525cbKJCoEhl.png

因此我们在目前检视额外去引入_ValidationScriptsPartial.cshtml

修改过後的Index.cshtml

@model ValidationMessageViewModel
<form>
    <div>
        <label asp-for="Name"></label>
        <input type="text" asp-for="Name" />
        <span asp-validation-for="Name"></span>
    </div>
    <div>
        <label asp-for="Age"></label>
        <input type="text" asp-for="Age" />
        <span asp-validation-for="Age"></span>
    </div>
    <div>
        <input type="submit" value="提交" />
    </div>
</form>

@section scripts{ 
    @{ 
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}

首先必填不可为空的验证效果
https://ithelp.ithome.com.tw/upload/images/20210928/20107452BiDk8Sq6wx.png

数值范围验证效果
https://ithelp.ithome.com.tw/upload/images/20210928/20107452QAfA6Cnbcs.png

预设范围会用系统提供的英文警示
也可以自订
调整後的ValidationMessageViewModel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Net5App6.Models
{
    public class ValidationMessageViewModel
    {
        [Display(Name="姓名")]
        [Required(ErrorMessage ="{0}不可为空!")]
        public string Name { get; set; }

        [Display(Name="年龄")]
        [Required(ErrorMessage ="{0}不可为空")]
        [Range(18,65,ErrorMessage ="{0}范围必须在{1}~{2}之间。")]
        public int Age { get; set; }
    }
}

再次运行测试验证效果
https://ithelp.ithome.com.tw/upload/images/20210928/20107452B8SERxEV8A.png

Server-Side验证

Controller部分 POST action method
可以透过ModelState.IsValid做验证

using Microsoft.AspNetCore.Mvc;
using Net5App6.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Net5App6.Controllers
{
    public class ValidationMessageController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(ValidationMessageViewModel model)
        {
            if (ModelState.IsValid)//pass server-side validation
            {
                return View(model);
            }
            return View(model);
        }
    }
}

ValidationSummaryTagHelper

Client-Side验证

Index.cshtml

@model ValidationMessageViewModel
<form>
    <div asp-validation-summary="All"></div>
    <div>
        <label asp-for="Name"></label>
        <input type="text" asp-for="Name" />
        <span asp-validation-for="Name"></span>
    </div>
    <div>
        <label asp-for="Age"></label>
        <input type="text" asp-for="Age" />
        <span asp-validation-for="Age"></span>
    </div>
    <div>
        <input type="submit" value="提交" />
    </div>
</form>

@section scripts{ 
    @{ 
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}

那预设最上面第一个div就会将所有错误警示都以方式呈现

https://ithelp.ithome.com.tw/upload/images/20210928/20107452dbRYDTMiWU.png

https://ithelp.ithome.com.tw/upload/images/20210928/201074526yqhuAy4w6.png

本篇已同步发表至个人blog
https://coolmandiary.blogspot.com/2021/08/net-core28validationmessagetaghelper.html


<<:  Day20-名称宇宙? 什麽是Namespace

>>:  Day 16:把做好的 HTML 加入 Angular 吧!

[Day19] Flutter with GetX something else

这篇主要讲GetX所提供, 自己有接触过的额外功能 为大家介绍 多国语系, 萤幕长宽, snackb...

食谱搜寻系统制作_上

制作目标 搜寻选择、使用者输入 Node.js从版本7开始提供readline模组,从可读串(例如p...

Leetcode 挑战 Day 18 [ 367. Valid Perfect Square ]

367. Valid Perfect Square 今天我们一起挑战leetcode第367题Val...

IOS、Python自学心得30天 Day-14 H5与Pb模型档案

前言: 因为内存不足以在训练的时候存 SavedModel模型 所以我分离出来 以.h5档案先做训练...

【Day 01】Zeze 的野望 - 开赛前言

前言 根据 NetMarketShare,Windows 在全球作业系统市场之中有统治性的地位,占了...