asp.net core2 mvc 基础教程--Model 验证 Again

时间:2020-07-15
本文章向大家介绍asp.net core2 mvc 基础教程--Model 验证 Again,主要包括asp.net core2 mvc 基础教程--Model 验证 Again使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

自定义验证 Attribute

  • Attribute,IModelValidator

示例:ValidUrlAttribute

public class ValidUrlAttribute : Attribute, IModelValidator

{

    public string ErrorMessage { get; set; }


    public IEnumerable<ModelValidationResult> Validate(

        ModelValidationContext context)
    {
        var url = context.Model as string;
        if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute))
        {
            return Enumerable.Empty<ModelValidationResult>();
        }

        return new List<ModelValidationResult>
        {
            new ModelValidationResult(string.Empty, ErrorMessage)
        };
    }
}

使用时标注在 ViewModel 等实体类的属性上即可:

[Display(Name = "封面地址")]

[Required(ErrorMessage = "{0}是必填项"), MaxLength(200, ErrorMessage = "{0}的长度不可超过{1}")]

//[DataType(DataType.Url)]

[ValidUrl(ErrorMessage = "这个URL不正确")]

public string CoverUrl { get; set; }

 

远程验证

  • [Remote]
  • 客户端调用 Action 方法进行验证(前台调用后台验证)

Action 中的方法:

 

[AcceptVerbs("Get", "Post")]

public async Task<IActionResult> CheckRoleExist([Bind("RoleName")]string roleName)
{
    var role = await _roleManager.FindByNameAsync(roleName);
    if (role != null) return Json("角色已经存在了");
    return Json(true);
}

标注属性:

public class RoleAddViewModel
{
    [Required]
    [Display(Name = "角色名称")]
    [Remote(nameof(RoleController.CheckRoleExist), "Role", ErrorMessage = "角色已存在")]
    public string RoleName { get; set; }

}

注:暂时没找到更优雅的方法获取到 "Role"。

 

原文地址:https://www.cnblogs.com/cqqinjie/p/13308495.html