Solved

Override ValidationSummary HtmlHelper

Posted on 2009-05-08
14
2,075 Views
Last Modified: 2013-11-08
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
Comment
Question by:veruthandai
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 6
14 Comments
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24352886
Hi veruthandai,
Give this a stab as a starter of your project.
http://www.codeproject.com/KB/validation/smartvalidationsummary.aspx
0
 

Author Comment

by:veruthandai
ID: 24354585
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
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24392362
Hi veruthandai,
Sorry for the delay. I just notice you're using MVC model. How your existing code flow look like?
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 

Author Comment

by:veruthandai
ID: 24395042
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
 
LVL 29

Accepted Solution

by:
David H.H.Lee earned 500 total points
ID: 24409028
0
 

Author Comment

by:veruthandai
ID: 24409030
Simply put, the HTML the ValidationSummary HTML helper makes is insufficient. I need to draw it myself - but overriding it is impossible.
0
 

Author Comment

by:veruthandai
ID: 24409062
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
 

Author Comment

by:veruthandai
ID: 24411615
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
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24419250
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
 

Author Comment

by:veruthandai
ID: 24421558
37
0
 

Author Comment

by:veruthandai
ID: 24426270
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
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24428998
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
 

Author Comment

by:veruthandai
ID: 24431766
Sorry, it's 38.
0
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24448313
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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

WHY MVC is the future technology... As many of you know, MVC is Model,View,Controller pattern. Model View Controller pattern was invented in a Smalltalk context at Xerox in late 1970s. Why is this buzz about MVC: --------------------------- …
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question