Get error message if ModelState.IsValid fails?

前端 未结 11 1268
离开以前
离开以前 2020-11-30 02:27

I have this function in my controller.

[HttpPost]
public ActionResult Edit(EmployeesViewModel viewModel)
{
    Employee employee = GetEmployee(viewModel.Empl         


        
相关标签:
11条回答
  • 2020-11-30 02:47
    ModelState.Values.SelectMany(v => v.Errors).ToList().ForEach(x => _logger.Error($"{x.ErrorMessage}\n"));
    
    0 讨论(0)
  • 2020-11-30 02:49

    If you're looking to generate a single error message string that contains the ModelState error messages you can use SelectMany to flatten the errors into a single list:

    if (!ModelState.IsValid)
    {
        var message = string.Join(" | ", ModelState.Values
            .SelectMany(v => v.Errors)
            .Select(e => e.ErrorMessage));
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
    }
    
    0 讨论(0)
  • 2020-11-30 02:50

    If Modal State is not Valid & the error cannot be seen on screen because your control is in collapsed accordion, then you can return the HttpStatusCode so that the actual error message is shown if you do F12. Also you can log this error to ELMAH error log. Below is the code

    if (!ModelState.IsValid)
    {
                  var message = string.Join(" | ", ModelState.Values
                                                .SelectMany(v => v.Errors)
                                                .Select(e => e.ErrorMessage));
    
                    //Log This exception to ELMAH:
                    Exception exception = new Exception(message.ToString());
                    Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
    
                    //Return Status Code:
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
    }
    

    But please note that this code will log all validation errors. So this should be used only when such situation arises where you cannot see the errors on screen.

    0 讨论(0)
  • 2020-11-30 02:51

    It is sample extension

    public class GetModelErrors
    {
        //Usage return Json to View :
        //return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
        public class KeyMessages
        {
            public string Key { get; set; }
            public string Message { get; set; }
        }
        private readonly ModelStateDictionary _entry;
        public GetModelErrors(ModelStateDictionary entry)
        {
            _entry = entry;
        }
    
        public int Count()
        {
            return _entry.ErrorCount;
        }
        public string Exceptions(string sp = "\n")
        {
            return string.Join(sp, _entry.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.Exception));
        }
        public string Messages(string sp = "\n")
        {
            string msg = string.Empty;
            foreach (var item in _entry)
            {
                if (item.Value.ValidationState == ModelValidationState.Invalid)
                {
                    msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
                }
            }
            return msg;
        }
    
        public List<KeyMessages> MessagesWithKeys(string sp = "<p> ● ")
        {
            List<KeyMessages> list = new List<KeyMessages>();
            foreach (var item in _entry)
            {
                if (item.Value.ValidationState == ModelValidationState.Invalid)
                {
                    list.Add(new KeyMessages
                    {
                        Key = item.Key,
                        Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
                    });
                }
            }
            return list;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 02:55

    Try

    ModelState.Values.First().Errors[0].ErrorMessage
    
    0 讨论(0)
提交回复
热议问题