asp.net-mvc 如何从 ASP.Net MVC modelState 获取所有错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1352948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:48:28  来源:igfitidea点击:

How to get all Errors from ASP.Net MVC modelState?

asp.net-mvcmodelstate

提问by chobo2

I want to get all the error messages out of the modelState without knowing the key values. Looping through to grab all the error messages that the ModelState contains.

我想在不知道键值的情况下从 modelState 中获取所有错误消息。循环获取 ModelState 包含的所有错误消息。

How can I do this?

我怎样才能做到这一点?

回答by mmutilva

Using LINQ:

使用LINQ

IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);

回答by Oren Trutner

foreach (ModelState modelState in ViewData.ModelState.Values) {
    foreach (ModelError error in modelState.Errors) {
        DoSomethingWith(error);
    }
}

See also How do I get the collection of Model State Errors in ASP.NET MVC?.

另请参阅如何在 ASP.NET MVC 中获取模型状态错误的集合?.

回答by Dunc

Building on the LINQ verison, if you want to join all the error messages into one string:

基于 LINQ 版本,如果您想将所有错误消息合并为一个字符串:

string messages = string.Join("; ", ModelState.Values
                                        .SelectMany(x => x.Errors)
                                        .Select(x => x.ErrorMessage));

回答by Yasser Shaikh

I was able to do this using a little LINQ,

我能够使用一点 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;
}

The above method returns a list of validation errors.

上述方法返回验证错误列表。

Further Reading :

进一步阅读:

How to read all errors from ModelState in ASP.NET MVC

如何从 ASP.NET MVC 中的 ModelState 读取所有错误

回答by Simon_Weaver

During debugging I find it useful to put a table at the bottom of each of my pages to show all ModelState errors.

在调试期间,我发现在每个页面的底部放置一个表格来显示所有 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>

回答by Alan Macdonald

As I discovered having followed the advice in the answers given so far, you can get exceptions occuring without error messages being set, so to catch all problems you really need to get both the ErrorMessage and the Exception.

正如我发现已经遵循了迄今为止给出的答案中的建议,您可以在没有设置错误消息的情况下发生异常,因此要捕获所有问题,您确实需要同时获取 ErrorMessage 和异常。

String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors)
                                                           .Select( v => v.ErrorMessage + " " + v.Exception));

or as an extension method

或作为扩展方法

public static IEnumerable<String> GetErrors(this ModelStateDictionary modelState)
{
      return modelState.Values.SelectMany(v => v.Errors)
                              .Select( v => v.ErrorMessage + " " + v.Exception).ToList();

}

回答by james31rock

In case anyone wants to return the Name of the Model property for binding the error message in a strongly typed view.

如果有人想返回模型属性的名称以在强类型视图中绑定错误消息。

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);
    }
}

This way you can actually tie the error in with the field that threw the error.

通过这种方式,您实际上可以将错误与引发错误的字段联系起来。

回答by Josh Sutterfield

Outputting just the Error messages themselves wasn't sufficient for me, but this did the trick.

仅输出错误消息本身对我来说是不够的,但这确实有效。

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));

回答by CodeArtist

For just in case someone need it i made and use the following static class in my projects

为了以防万一有人需要它,我制作并在我的项目中使用以下静态类

Usage example:

用法示例:

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;

Class:

班级:

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();
    }
}

回答by Steve Lydford

Useful for passing array of error messages to View, perhaps via Json:

用于将错误消息数组传递给 View,可能是通过 Json:

messageArray = this.ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors, (modelState, error) => error.ErrorMessage).ToArray();