4

I have added a key-value pair in the action result like this:

[HttpPost, Authorize]
 public ActionResult ListFacilities(int countryid)
{
...
 ModelState.AddModelError("Error","No facilities reported in this country!");
...
}

I have some cumbersome codes like these in a unit test to :

 public void ShowFailforFacilities()
 {
 //bogus data
 var facilities = controller.ListFacilities(1) as PartialViewResult;
 Assert.AreSame("No facilities reported in this country!",
 facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage);
 }

Of course, it works whenever I have only one error.
I don't like facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage.

Is there an easier way for me to fetch the value from that dictionary?

tereško
58.5k26 gold badges101 silver badges152 bronze badges
asked Apr 11, 2011 at 3:26

2 Answers 2

13

Your FirstOrDefault isn't needed, because you'll get a NullReferenceException when accessing ErrorMessage. You can just use First().

Either way, I couldn't find any built-in solution. What I've done instead is create an extension method:

public static class ExtMethod
 {
 public static string GetErrorMessageForKey(this ModelStateDictionary dictionary, string key)
 {
 return dictionary[key].Errors.First().ErrorMessage;
 }
 }

Which works like this:

ModelState.GetErrorMessageForKey("error");

If you need better exception handling, or support for multiple errors, its easy to extend...

If you want this to be shorter you can create an extension method for the ViewData...

public static class ExtMethod
 {
 public static string GetModelStateError(this ViewDataDictionary viewData, string key)
 {
 return viewData.ModelState[key].Errors.First().ErrorMessage;
 }
 }

and usage:

ViewData.GetModelStateError("error");
answered Apr 11, 2011 at 7:26
Sign up to request clarification or add additional context in comments.

2 Comments

0

Have you tried this?

// Note: In this example, "Error" is the name of your model property.
facilities.ViewData.ModelState["Error"].Value
facilities.ViewData.ModelState["Error"].Error
Adrian Thompson Phillips
7,1987 gold badges43 silver badges72 bronze badges
answered Apr 11, 2011 at 6:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.