ViewModel类:
/// <summary> /// 评论用验证视图 /// </summary> public partial class VCreateShopComment { [Required(AllowEmptyStrings = false, ErrorMessage = "旺旺是必须的")] public string WW { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "必须评论")] [StringLength(200, ErrorMessage = "评论内容不能超过{0}字")] public string CommentText { get; set; } [Range(1, 5, ErrorMessage = "评分要在{1}到{2}之间")] public short Score { get; set; } //[Range(0, int.MaxValue, ErrorMessage = "您的账户无效")] public int ID{ get; set; } }
控制器
[HttpPost] public ActionResult Add(VCreateShopComment v) { if (ModelState.IsValid) { //做爱做的事 } StringBuilder sb = new StringBuilder(); var errors = ModelState.Values; foreach (var item in errors) { foreach (var item2 in item.Errors) {
if (!item2.ErrorMessage.IsNullOrWhiteSpace()) { sb.AppendLine(item2.ErrorMessage + "<br />"); }
} } return Content(sb.ToString()); }
错误的输出用2次遍历就行了,前提是,对于每个验证特性ErrorMessage 是要有的
时间: 2024-11-08 21:00:17