Click here to Skip to main content
15,893,588 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.IO;
using System.Web.Mvc;

namespace MvcControls
{
	public class MvcCheckBox : MvcInput
	{
		#region MvcControl Members

		protected override void RenderHtml(StringWriter writer, ViewContext viewContext)
		{
			// When a checkbox is unchecked, it doesn't get included in the post data or query string.
			// Render a hidden element with the same name as the checkbox but set the "value" attribute to "false".
			// A value of "true" or "true,false" will be included in the form data (checked or unchecked respectively).
			TagBuilder hiddenCheckBox = new TagBuilder("input");
			hiddenCheckBox.Attributes["name"] = Name;
			hiddenCheckBox.Attributes["type"] = "hidden";
			hiddenCheckBox.Attributes["value"] = "false";

			writer.Write(hiddenCheckBox.ToString(TagRenderMode.SelfClosing));
		}

		#endregion

		public bool Checked
		{
			set
			{
				if (value)
				{
					Attributes["checked"] = "checked";
				}
				else
				{
					Attributes.Remove("checked");
				}
			}
		}

		public object Value
		{
			set { Attributes.Merge("value", value); }
		}

		public MvcCheckBox(string name)
			: base(InputType.CheckBox, name)
		{
			// The value SHOULD always be set to true, even when it isn't checked.
			// Use caution when overriding Value.
			Value = "true";
		}
	}
}

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