Click here to Skip to main content
15,892,480 members
Articles / Web Development / XHTML

Custom controls in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.76/5 (31 votes)
8 Jan 2009CPOL8 min read 159.6K   2.9K   95  
Control library for rendering custom HTML in ASP.NET MVC applications.
using System;
using System.IO;
using System.Web.Mvc;

namespace MvcControls
{
	public class MvcValidationMessage : MvcControl
	{
		#region MvcControlBuilder Members

		protected override void Initialise(ViewContext viewContext)
		{
			if (viewContext == null)
			{
				throw new ArgumentNullException("viewContext");
			}

			ViewDataDictionary viewData = viewContext.ViewData;

			if (!viewData.ModelState.ContainsKey(ModelName))
			{
				return;
			}

			ModelErrorCollection modelErrors = viewData.ModelState.GetErrors(ModelName);

			if (modelErrors == null || modelErrors.Count == 0)
			{
				return;
			}

			string errorMessage = string.IsNullOrEmpty(ErrorMessage) ? modelErrors[0].ErrorMessage : ErrorMessage;

			SetInnerText(errorMessage);
			Title = errorMessage;
		}

		#endregion

		protected string ModelName { get; private set; }

		protected string ErrorMessage { get; private set; }

		public MvcValidationMessage(string modelName)
			: this(modelName, null) { }

		public MvcValidationMessage(string modelName, string errorMessage)
			: base("span")
		{
			if (string.IsNullOrEmpty(modelName))
			{
				throw new ArgumentException("Value cannot be null or empty.", "modelName");
			}

			// Set a default CSS class.
			Class = "field-validation-error";

			ModelName = modelName;
			ErrorMessage = errorMessage;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Kingdom United Kingdom
Software engineer.

Blog: http://andrewgunn.blogspot.com/
Twitter: andrewgunn

Comments and Discussions