1

I have the following action method:-

 public ActionResult AddServerToRack(AddServerToRack s)
        {

            if (ModelState.IsValid)
            {
                try
                {
                   // code goes here
                }
            }
            var errorDesc = ModelState.Select(a=>a.Value.Errors.Select(a2=>a2.ErrorMessage)).ToList();
            string desc = "";
            foreach (var i in errorDesc)
            {
                desc = desc + " " + i.ToString();
            }
            return Json(new { IsSuccess = false, description = desc}, JsonRequestBehavior.AllowGet);
        }

what i am trying to do is to get all the error messages inside the model state and send them as a json object. but currently i fail to get the description of the error message using the foreach at the end of my action method. so can anyone advice , how i can get all the modelstates error message description .? Thanks

2 Answers 2

5

This will work for you :-

foreach (ModelState modelState in ViewData.ModelState.Values) {
string desc = "";
   foreach (ModelError error in modelState.Errors) { 
    desc = desc + " " + error.ErrorMessage.ToString();
  }
}
1
  • i modified you code by using error.ErrorMessage.toString() and it worked, can you edit you answer, so that i can mark it a answered..
    – John John
    Jul 23, 2014 at 10:29
2

Here is a .Net LINQ Expression that does the same as the answer from Kartikeya Khosla above.

  string desc = ViewData.ModelState.Values.SelectMany(modelState => 
                modelState.Errors).Aggregate("", (current, error) => 
                current + " " + error.ErrorMessage.ToString());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.