我想在不知道键值的情况下从modelState中获取所有错误消息。循环以获取ModelState包含的所有错误消息。
我该怎么做?
答案 0 :(得分:475)
使用LINQ:
IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
答案 1 :(得分:472)
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
DoSomethingWith(error);
}
}
另见How do I get the collection of Model State Errors in ASP.NET MVC?。
答案 2 :(得分:173)
在LINQ版本的基础上,如果要将所有错误消息加入一个字符串:
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
答案 3 :(得分:25)
我能够使用一点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;
}
上述方法返回验证错误列表。
进一步阅读:
答案 4 :(得分:13)
在调试过程中,我发现在每个页面的底部放一个表来显示所有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>
答案 5 :(得分:11)
正如我发现在目前为止给出的答案中已经遵循了建议,您可以在没有设置错误消息的情况下发生异常,因此要捕获所有需要同时获取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();
}
答案 6 :(得分:7)
如果有人想要返回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);
}
}
这样,您实际上可以将错误与引发错误的字段联系起来。
答案 7 :(得分:4)
这扩展了@Dunc的答案。请参阅xml doc comments
// 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;
}
}
答案 8 :(得分:4)
输出错误消息本身对我来说不够,但这就行了。
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));
答案 9 :(得分:4)
为了以防有人需要它,我在我的项目中使用了以下静态类
用法示例:
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();
}
}
答案 10 :(得分:4)
这也有效:
var query = from state in ModelState.Values
from error in state.Errors
select error.ErrorMessage;
var errors = query.ToArray(); // ToList() and so on...
答案 11 :(得分:3)
<div class="text-danger" style="direction:rtl" asp-validation-summary="All"></div>
仅使用asp-validation-summary标记助手
答案 12 :(得分:3)
任何人都在寻找 ASP.NET Core 3.1。比上面的答案略有更新。我发现这就是 [ApiController] 返回的内容
Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();
foreach (KeyValuePair<string, ModelStateEntry> kvp in ViewData.ModelState)
{
string key = kvp.Key;
ModelStateEntry entry = kvp.Value;
if (entry.Errors.Count > 0)
{
List<string> errorList = new List<string>();
foreach (ModelError error in entry.Errors)
{
errorList.Add(error.ErrorMessage);
}
errors[key] = errorList;
}
}
return new JsonResult(new {Errors = errors});
答案 13 :(得分:2)
用于将错误消息数组传递给View,可能是通过Json:
messageArray = this.ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors, (modelState, error) => error.ErrorMessage).ToArray();
答案 14 :(得分:2)
此外,ModelState.Values.ErrorMessage
可能为空,但ModelState.Values.Exception.Message
可能表示错误。
答案 15 :(得分:0)
在您的实现中,您缺少静态类,这应该是。
if (!ModelState.IsValid)
{
var errors = ModelStateErrorHandler.GetModelErrors(this.ModelState);
return Json(new { errors });
}
,而
if (!ModelState.IsValid)
{
var errors = ModelState.GetModelErrors();
return Json(new { errors });
}
答案 16 :(得分:0)
我不知道这是我的问题,有时我在ModelState的ErrorMessage部分中收到消息,有时在ModelState错误的异常消息中得到消息。
因此,我已经创建了一种可以同时处理这两种情况的方法。希望这对这里的所有人都有帮助。
public static string GetErrorMessageFromModelState(ModelStateDictionary modelState)
{
string errorMessage = string.Empty;
try
{
string[] errorMessageList = (from m in modelState
where m.Value.Errors.Count > 0
select string.Join(", ", m.Value.Errors.Select(x =>
!string.IsNullOrEmpty(x.ErrorMessage) ? x.ErrorMessage : !string.IsNullOrEmpty(x.Exception.Message) ?
x.Exception.Message.Split('\'').Length > 0 ? x.Exception.Message.Split('\'')[1].ToString() : m.Key.Split('.').Length > 1 ?
m.Key.Split('.')[1] : m.Key.Split('.')[0] : m.Key.Split('.')[0]))).ToArray();
errorMessage = string.Format("Error in Field(s): " + string.Join(", ", errorMessageList) + " {0} required.", (errorMessageList.Count() > 1 ? "are" : "is"));
}
catch (Exception ex)
{
errorMessage = ex.Message;
if (ex.InnerException != null)
errorMessage += Environment.NewLine + ex.InnerException;
}
return errorMessage;
}
答案 17 :(得分:0)
var x = new Dictionary<string,string>();
for (var b = 0; b < ViewData.ModelState.Values.Count(); b++)
{
if (ViewData.ModelState.Values.ElementAt(b).Errors.Count() > 0)
x.Add(ViewData.ModelState.Keys.ElementAt(b), String.Join(",", ViewData
.ModelState.Values.ElementAt(b).Errors.Select(c => c.ErrorMessage)));
}
答案 18 :(得分:-1)
var result = string.Join(',',ModelState.Values.SelectMany(v => v.Errors).Select(a=>a.ErrorMessage));