Creating Required Literal for MVC with Razor rendering engine

In web applications, It is became a standard to have a symbol indicating if the field is required or not. This symbol maight be a star, icon or any verbiage that a client ma requested to have. It is a good practice to have the logic that render this symbol in one place and have all of your views using it. You can do that easily in standard ASPX pages, and it is the same on MVC using Razer rendering engine (cshtml/vbhtml). For MVC you need to create a custom HTML helper that do the job for you, and using it in your views cross the board. Below is a sample HTML helper method


public static MvcHtmlString RequiredFieldIcon(this HtmlHelper helper)
TagBuilder tag = new TagBuilder(“span”);
tag.Attributes.Add(“title”, “Field is required”);
tag.SetInnerText(“>> “);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));

In above method, the symbol is as simple as ‘>>’ in red color; using CSS class for that. it might be more complicated UI control and you can customize it based on your requirement. You can use this method just as if it is one of the out of the box HTML helpers that shipped with MVC; you just need to make sure you are including the namespace of the class that hosting this HTML helper method.