locked
Get the Key value of the Model error RRS feed

  • Question

  • User265788195 posted

    Hi,

    I am getting list of Model Errors in string list.
    The want to store the key value attached to the model error.
    Lets say the ErrorMessage is "FirstName is required", I want to know it by some key
    so that I can place the focus on FirstName input box.
    So I wnat to pass that key as well thru Json here. 

    var errorList = new List<string>();

                    foreach (ModelState modelState in ViewData.ModelState.Values)
                    {
                        foreach (ModelError error in modelState.Errors)
                        {
                            errorList.Add(error.ErrorMessage);
                        }
                    }

                    return Json(new { personId = -1, errorMessage = errorList.ToList() });

    Friday, May 18, 2012 11:27 AM

Answers

  • User1779161005 posted

    Didn't test it, but will something like this work:

    var errors =
        from item in ModelState
        where item.Value.Errors.Count > 0
        select item.Key;
    var keys = errors.ToArray();

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 18, 2012 4:06 PM