ASP.NET MVC验证所有属性是否合法
1.实现代码:
/// <summary> /// 验证所有属性是否合法 /// </summary> /// <param name="modelState"></param> /// <returns></returns> public string GetValidMsg(ModelStateDictionary modelState) { StringBuilder sb = new StringBuilder(); //遍历每个属性 foreach (var propName in modelState.Keys) { //属性相关的错误消息 if (modelState[propName].Errors.Count <= 0) { continue; } sb.Append("字段“").Append(propName).Append("”输入的值有误,"); //遍历每个错误消息(因为一个属性可能有多个错误消息) foreach (ModelError modelError in modelState[propName].Errors) { sb.Append(modelError.ErrorMessage); } sb.AppendLine(); } return sb.ToString(); }
2.调用:
if (ModelState.IsValid) { ...... } else { resultState.Message = GetValidMsg(ModelState); //ModelState为Controller下的属性,所有的控制器都继承了Controller }
return Json(resultState);