Your FirstOrDefault is not required because when you access ErrorMessage you will get a NullReferenceException. You can just use First ().
In any case, I could not find a built-in solution. Instead, I created an extension method:
public static class ExtMethod { public static string GetErrorMessageForKey(this ModelStateDictionary dictionary, string key) { return dictionary[key].Errors.First().ErrorMessage; } }
Which works as follows:
ModelState.GetErrorMessageForKey("error");
If you need more efficient exception handling or support for multiple errors, it's easy to extend it ...
If you want this to be shorter, you can create an extension method for ViewData ...
public static class ExtMethod { public static string GetModelStateError(this ViewDataDictionary viewData, string key) { return viewData.ModelState[key].Errors.First().ErrorMessage; } }
and use:
ViewData.GetModelStateError("error");
source share