标签:style text com ini cti password imu redirect pre
using System.ComponentModel.DataAnnotations;
namespace Demo.Models
{
public class User
{
[Key]
public int Id { get; set; }
[Display(Name = "登录账号")]
[Required(ErrorMessage ="登录账号必填")]
[StringLength(15, ErrorMessage = "字符长度不能超过15个字")]
public string LoginId { get; set; }
public string PassWord { get; set; }
public string Name { get; set; }
[Range(minimum:1,maximum:100,ErrorMessage ="请输入1到100的数字")]
public int Age { get; set; }
}
}
代码中部分数据注释的作用效果如上图所示,更多注释可以使用百度,例如远程验证、邮箱地址、正则表达式等
<form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="LoginId" class="control-label"></label> <input asp-for="LoginId" class="form-control" /> <span asp-validation-for="LoginId" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="PassWord" class="control-label"></label> <input asp-for="PassWord" class="form-control" /> <span asp-validation-for="PassWord" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Age" class="control-label"></label> <input asp-for="Age" class="form-control" /> <span asp-validation-for="Age" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form>
注意点:
1.aspnetcore用<form asp-action="Create">这种写法,自动防范了请求伪造(csxf攻击)
2.<span asp-validation-for="PassWord" class="text-danger"></span>这种区块就是用于显示验证错误信息的地方,错误信息会自动加入到span标签中
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,LoginId,PassWord,Name,Age")] User user) { if (string.IsNullOrWhiteSpace(user.Name)) { //名称需要填写,此处是为了演示AddModelError方法,实际Name必填应使用Required注释控制 //ModelState.AddModelError("", "名称需要填写"); ModelState.AddModelError(nameof(Models.User.Name), "名称需要填写"); return View(nameof(Create)); } if (ModelState.IsValid) { _context.Add(user); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(user); }
使用ModelState.AddModelError(nameof(Models.User.Name), "名称需要填写");方法提示错误信息,会把错误信息给到对应span中
AddModelError第一个参数,如果是空字符串,则会把错误信息给到<div asp-validation-summary="ModelOnly" class="text-danger"></div>中
标签:style text com ini cti password imu redirect pre
原文地址:https://www.cnblogs.com/kasnti/p/10865282.html