Skip to content

Instantly share code, notes, and snippets.

@osya
Last active October 20, 2016 09:47
Show Gist options
  • Save osya/f963056860864b6e4fb408da9775a453 to your computer and use it in GitHub Desktop.
Save osya/f963056860864b6e4fb408da9775a453 to your computer and use it in GitHub Desktop.
ValidateMessageFor which shows multiple messages #CSharp
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