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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With