Last active
October 20, 2016 09:47
-
-
Save osya/f963056860864b6e4fb408da9775a453 to your computer and use it in GitHub Desktop.
ValidateMessageFor which shows multiple messages #CSharp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ValidateMessagesFor | |
{ | |
public static MvcHtmlString ValidationMessagesFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) | |
{ | |
var propertyName = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName; | |
var modelState = htmlHelper.ViewData.ModelState; | |
if (!modelState.ContainsKey(propertyName) || modelState[propertyName].Errors.Count <= 1) | |
return htmlHelper.ValidationMessageFor(expression, null, | |
htmlAttributes as IDictionary<string, object> ?? htmlAttributes); | |
var msgs = new StringBuilder(); | |
foreach (var error in modelState[propertyName].Errors) | |
{ | |
msgs.AppendLine(error.ErrorMessage); | |
} | |
// Return standard ValidationMessageFor, overriding the message with our concatenated list of messages. | |
return htmlHelper.ValidationMessageFor(expression, msgs.ToString(), htmlAttributes as IDictionary<string, object> ?? htmlAttributes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment