如何从ASP.Net MVC ModelState中所有的错误?(How to get all Er

2019-06-21 07:03发布

我想走出ModelState中的所有错误消息不知道键值。 通过循环抓住所有的ModelState中包含错误信息。

我怎样才能做到这一点?

Answer 1:

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

另见我如何获得模型状态错误的收集ASP.NET MVC? 。



Answer 2:

使用LINQ :

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


Answer 3:

建立在LINQ verison,如果你想加入所有的出错信息为一个字符串:

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


Answer 4:

我可以用这一点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;
}

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

延伸阅读:

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



Answer 5:

在调试过程中我觉得有用把一个表中的每个我的网页底部显示所有的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>


Answer 6:

正如我发现已经遵循目前给出的答案的建议,你可以得到例外,而不设置错误信息存在的,因此抓住你真的需要得到双方的ErrorMessage和异常的所有问题。

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

}


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

这种方式可以实际上抛出错误的字段配合误差。



Answer 8:

而这也工作:

var query = from state in ModelState.Values
    from error in state.Errors
    select error.ErrorMessage;
var errors = query.ToArray(); // ToList() and so on...


Answer 9:

这是在从@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;            
    }
}


Answer 10:

为了以防万一有人需要它,我提出和使用下面的静态类在我的项目

用法示例:

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


Answer 11:

只是输出错误信息本身是不够的,对我来说这并获得成功。

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


Answer 12:

有用传递错误信息的阵列通过JSON查看,可能是:

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


Answer 13:

此外, ModelState.Values.ErrorMessage可能是空的,但ModelState.Values.Exception.Message可指示错误。



Answer 14:

在你实现你缺少静态类,这应该是。

if (!ModelState.IsValid)
{
    var errors =  ModelStateErrorHandler.GetModelErrors(this.ModelState);
    return Json(new { errors });
}

if (!ModelState.IsValid)
{
    var errors = ModelState.GetModelErrors();
    return Json(new { errors });
}


Answer 15:

我不知道这是在我的情况的问题,有时我在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;
    }


文章来源: How to get all Errors from ASP.Net MVC modelState?