我想在不知道键值的情况下获得modelState中的所有错误消息。循环获取ModelState包含的所有错误消息。
我该怎么做呢?
我想在不知道键值的情况下获得modelState中的所有错误消息。循环获取ModelState包含的所有错误消息。
我该怎么做呢?
当前回答
使用字段名和错误消息获取错误
var errors = new List<ErrorDto>();
foreach (KeyValuePair<string, ModelStateEntry> kvp in context.ModelState)
{
if (kvp.Value.Errors.Count > 0)
{
errors.Add(new ErrorDto()
{
FieldName = kvp.Key,
ErrorMessage = string.Join(",", kvp.Value.Errors.Select(v => v.ErrorMessage))
});
}
}
误差模型
public class ErrorDto
{
public string FieldName { get; set; }
public string ErrorMessage { get; set; }
}
其他回答
对于AJAX请求更好的解决方案:
public IActionResult Demo(DemoInfo formData)
{
if (!ModelState.IsValid)
{
IEnumerable<object> formErrors = ModelState.Select((s) => new {
fieldName = s.Key,
fieldValue = s.Value.RawValue,
fieldMessage = s.Value.Errors.FirstOrDefault()?.ErrorMessage
});
return Json(new { formValid = 0, formErrors });
}
return Json(new { formValid = 1 });
}
回应格式为:
{"formValid":0,
"formErrors":[{
"fieldName":"name of field from object",
"fieldValue":"value from browser",
"fieldMessage":null /*Error message from model annotations if field is valid the value will be null */
}]
}
有关Func<>的更多详细信息,请查看本页:Func<TSource,Int32,TResult>)
我可以用一点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;
}
上面的方法返回一个验证错误列表。
进一步阅读:
如何在ASP中读取ModelState中的所有错误。NET MVC
在您的实现中,您缺少静态类,这应该是。
if (!ModelState.IsValid)
{
var errors = ModelStateErrorHandler.GetModelErrors(this.ModelState);
return Json(new { errors });
}
而
if (!ModelState.IsValid)
{
var errors = ModelState.GetModelErrors();
return Json(new { errors });
}
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
DoSomethingWith(error);
}
}
请参见如何在ASP中获取模型状态错误的集合。净MVC ?。
为了以防有人需要它,我在我的项目中创建并使用下面的静态类
使用的例子:
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();
}
}