如何从ASP.Net MVC modelState获取所有错误?
我想在不知道键值的情况下将所有错误消息从modelState中移出。 循环获取ModelState包含的所有错误消息。
我该怎么做?
foreach (ModelState modelState in ViewData.ModelState.Values) { foreach (ModelError error in modelState.Errors) { DoSomethingWith(error); } }
另请参见如何获取ASP.NET MVC中的模型状态错误的集合? 。
使用LINQ :
IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
build立在LINQ版本之上,如果你想把所有的错误消息合并成一个string:
string messages = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage));
我能够使用一点LINQ来做到这一点,
public static List<string> GetErrorListFromModelState (ModelStateDictionary modelState) { var query = from state in modelState.Values from error in state.Errors select error.ErrorMessage; var errorList = query.ToList(); return errorList; }
上面的方法返回一个validation错误列表。
进一步阅读:
如何从ASP.NET MVC中的ModelState读取所有错误
在debugging过程中,我发现在每个页面底部放置一个表格可以显示所有的ModelState错误。
<table class="model-state"> @foreach (var item in ViewContext.ViewData.ModelState) { if (item.Value.Errors.Any()) { <tr> <td><b>@item.Key</b></td> <td>@((item.Value == null || item.Value.Value == null) ? "<null>" : item.Value.Value.RawValue)</td> <td>@(string.Join("; ", item.Value.Errors.Select(x => x.ErrorMessage)))</td> </tr> } } </table> <style> table.model-state { border-color: #600; border-width: 0 0 1px 1px; border-style: solid; border-collapse: collapse; font-size: .8em; font-family: arial; } table.model-state td { border-color: #600; border-width: 1px 1px 0 0; border-style: solid; margin: 0; padding: .25em .75em; background-color: #FFC; } </style>
正如我发现按照目前给出的答案中的build议,你可以得到exception发生没有错误消息被设置,所以要捕获所有的问题,你真的需要得到ErrorMessage和exception。
String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors) .Select( v => v.ErrorMessage + " " + v.Exception));
或作为扩展方法
public static IEnumerable<String> GetErrors(this ModelStateDictionary modelState) { return modelState.Values.SelectMany(v => v.Errors) .Select( v => v.ErrorMessage + " " + v.Exception).ToList(); }
这也是有效的
var query = from state in ModelState.Values from error in state.Errors select error.ErrorMessage; var errors = query.ToArray(); // ToList() and so on...
这正在扩展@Dunc的答案。 请参阅xml文档注释
// ReSharper disable CheckNamespace using System.Linq; using System.Web.Mvc; public static class Debugg { /// <summary> /// This class is for debugging ModelState errors either in the quick watch /// window or the immediate window. /// When the model state contains dozens and dozens of properties, /// it is impossible to inspect why a model state is invalid. /// This method will pull up the errors /// </summary> /// <param name="modelState">modelState</param> /// <returns></returns> public static ModelError[] It(ModelStateDictionary modelState) { var errors = modelState.Values.SelectMany(x => x.Errors).ToArray(); return errors; } }
为了防止有人需要它,我在我的项目中使用了下面的静态类
用法示例:
if (!ModelState.IsValid) { var errors = ModelState.GetModelErrors(); return Json(new { errors }); }
Usings:
using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using WebGrease.Css.Extensions;
类:
public static class ModelStateErrorHandler { /// <summary> /// Returns a Key/Value pair with all the errors in the model /// according to the data annotation properties. /// </summary> /// <param name="errDictionary"></param> /// <returns> /// Key: Name of the property /// Value: The error message returned from data annotation /// </returns> public static Dictionary<string, string> GetModelErrors(this ModelStateDictionary errDictionary) { var errors = new Dictionary<string, string>(); errDictionary.Where(k => k.Value.Errors.Count > 0).ForEach(i => { var er = string.Join(", ", i.Value.Errors.Select(e => e.ErrorMessage).ToArray()); errors.Add(i.Key, er); }); return errors; } public static string StringifyModelErrors(this ModelStateDictionary errDictionary) { var errorsBuilder = new StringBuilder(); var errors = errDictionary.GetModelErrors(); errors.ForEach(key => errorsBuilder.AppendFormat("{0}: {1} -", key.Key,key.Value)); return errorsBuilder.ToString(); } }
如果有人想在强types视图中返回Model属性的名称来绑定错误消息。
List<ErrorResult> Errors = new List<ErrorResult>(); foreach (KeyValuePair<string, ModelState> modelStateDD in ViewData.ModelState) { string key = modelStateDD.Key; ModelState modelState = modelStateDD.Value; foreach (ModelError error in modelState.Errors) { ErrorResult er = new ErrorResult(); er.ErrorMessage = error.ErrorMessage; er.Field = key; Errors.Add(er); } }
通过这种方式,您可以将错误与发生错误的字段相结合。
只输出错误信息本身对我来说是不够的,但是这个技巧。
var modelQuery = (from kvp in ModelState let field = kvp.Key let state = kvp.Value where state.Errors.Count > 0 let val = state.Value.AttemptedValue ?? "[NULL]" let errors = string.Join(";", state.Errors.Select(err => err.ErrorMessage)) select string.Format("{0}:[{1}] (ERRORS: {2})", field, val, errors)); Trace.WriteLine(string.Join(Environment.NewLine, modelQuery));
用于将错误消息数组传递给View,可能通过Json:
messageArray = this.ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors, (modelState, error) => error.ErrorMessage).ToArray();
另外, ModelState.Values.ErrorMessage
可能是空的,但是ModelState.Values.Exception.Message
可能指示错误。
在你的实现中你缺less静态类,这应该是。
if (!ModelState.IsValid) { var errors = ModelStateErrorHandler.GetModelErrors(this.ModelState); return Json(new { errors }); }
宁
if (!ModelState.IsValid) { var errors = ModelState.GetModelErrors(); return Json(new { errors }); }