Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2130
  • Last Modified:

Override ValidationSummary HtmlHelper

I'm trying to figure out a way to change the CSS classes for ValidationSummary htmlHelper in ASP.NET MVC. I know it has some 'preset' css styles, but for some purposes, I need to have more control over the rendering.

Does anyone have an idea of how to do this? I've thought about extension methods, but I'm having trouble figuring out where to start.
0
veruthandai
Asked:
veruthandai
  • 8
  • 6
1 Solution
 
David H.H.LeeCommented:
Hi veruthandai,
Give this a stab as a starter of your project.
http://www.codeproject.com/KB/validation/smartvalidationsummary.aspx
0
 
veruthandaiAuthor Commented:
These ideas will work with the MVC model too? The Html Helper Validator is just that, a helper, not a class. How am I able to inherit from it?
0
 
David H.H.LeeCommented:
Hi veruthandai,
Sorry for the delay. I just notice you're using MVC model. How your existing code flow look like?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
veruthandaiAuthor Commented:
I do not yet have an existing code flow. I'm trying to figure out what I want to do based on what can be done with the ValidationSummary.
0
 
David H.H.LeeCommented:
0
 
veruthandaiAuthor Commented:
Simply put, the HTML the ValidationSummary HTML helper makes is insufficient. I need to draw it myself - but overriding it is impossible.
0
 
veruthandaiAuthor Commented:
I've downloaded the MVC source from codeplex and tried to mimic the ValidationSummary HTML Helper from it - but the problem is that some of the stuff it has to access is private.
I guess what I need to know is how to re-write the ValidationSummary output html.
0
 
veruthandaiAuthor Commented:
Here we go, I dug it out. This is the code that generates the ValidationSummary.
I am trying to write my own Extension - but I keep hitting this wall. "MvcResources is not available due to its protection level".

namespace System.Web.Mvc.Html
{
	using System;
	using System.Collections.Generic;
	using System.Diagnostics.CodeAnalysis;
	using System.Globalization;
	using System.Text;
	using System.Web.Mvc.Resources;
	using System.Web.Routing;
 
	public static partial class ValidationExtensions
	{
		private static string _resourceClassKey;
 
		public static string ResourceClassKey
		{
			get
			{
				return _resourceClassKey ?? String.Empty;
			}
			set
			{
				_resourceClassKey = value;
			}
		}
 
		private static string GetInvalidPropertyValueResource(HttpContextBase httpContext)
		{
			string resourceValue = null;
			if (!String.IsNullOrEmpty(ResourceClassKey) && (httpContext != null))
			{
				// If the user specified a ResourceClassKey try to load the resource they specified.
				// If the class key is invalid, an exception will be thrown.
				// If the class key is valid but the resource is not found, it returns null, in which
				// case it will fall back to the MVC default error message.
				resourceValue = httpContext.GetGlobalResourceObject(ResourceClassKey, "InvalidPropertyValue", CultureInfo.CurrentUICulture) as string;
			}
			return resourceValue ?? MvcResources.Common_ValueNotValidForProperty;
		}
 
		private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState)
		{
			if (!String.IsNullOrEmpty(error.ErrorMessage))
			{
				return error.ErrorMessage;
			}
			if (modelState == null)
			{
				return null;
			}
 
			string attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;
			return String.Format(CultureInfo.CurrentCulture, GetInvalidPropertyValueResource(httpContext), attemptedValue);
		}
 
		public static string ValidationSummary(this HtmlHelper htmlHelper, string message, IDictionary<string, object> htmlAttributes)
		{
			// Nothing to do if there aren't any errors
			if (htmlHelper.ViewData.ModelState.IsValid)
			{
				return null;
			}
 
			string messageSpan;
			if (!String.IsNullOrEmpty(message))
			{
				TagBuilder spanTag = new TagBuilder("span");
				spanTag.MergeAttributes(htmlAttributes);
				spanTag.MergeAttribute("class", HtmlHelper.ValidationSummaryCssClassName);
				spanTag.SetInnerText(message);
				messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;
			}
			else
			{
				messageSpan = null;
			}
 
			StringBuilder htmlSummary = new StringBuilder();
			TagBuilder unorderedList = new TagBuilder("ul");
			unorderedList.MergeAttributes(htmlAttributes);
			unorderedList.MergeAttribute("class", HtmlHelper.ValidationSummaryCssClassName);
 
			foreach (ModelState modelState in htmlHelper.ViewData.ModelState.Values)
			{
				foreach (ModelError modelError in modelState.Errors)
				{
					string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);
					if (!String.IsNullOrEmpty(errorText))
					{
						TagBuilder listItem = new TagBuilder("li");
						listItem.SetInnerText(errorText);
						htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
					}
				}
			}
		}
	}
}

Open in new window

0
 
David H.H.LeeCommented:
Hi veruthandai,
May i know which line of code hitting that error that mentioned for "MvcResources is not available due to its protection level"?
0
 
veruthandaiAuthor Commented:
37
0
 
veruthandaiAuthor Commented:
I'm sorry, nothing here has led me to the solution. The simple fact is that three styles are not enough to customize it. The styles that microsoft provides do not give enough flexibility - I have to be able to override both the HTML output and the CSS classes they refer to.
0
 
David H.H.LeeCommented:
Hi veruthandai,
I understood that you're trying to include the preferred style based on the existing shortcomings. But, line 37 is "{" according the code that posted?
0
 
veruthandaiAuthor Commented:
Sorry, it's 38.
0
 
David H.H.LeeCommented:
Hi veruthandai,
I'm not veteran in MVC model. But, i've come across this article, you can check if this assist in your research: http://mikehadlow.blogspot.com/2008/09/form-validation-with-mvc-framework.html
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 8
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now