The intent of this article is to explain how to create custom HTML Helpers, so that we can use within the MVC views, using HTML Helpers class we can reduce the large amount of typing of HTML tags.
HTML Helpers
A HTML Helper is just a method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input> and <img> tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data.
The following are some of the standard HTML Helpers already included in ASP.NET MVC:
- Html.ActionLink()
- Html.BeginForm()
- Html.CheckBox()
- Html.DropDownList()
- Html.EndForm()
- Html.Hidden()
- Html.ListBox()
- Html.Password()
- Html.RadioButton()
- Html.TextArea()
- Html.TextBox()
Creating HTML Helpers with Static Methods
The easiest way to create a new HTML Helper is to create a static method that returns a string. Imagine, for example, that you decide to create some new HTML Helpers that render an HTML <Image> tag, HTML <ActionLink> tag, HTML <ActionLinkSortable> tag, HTML <DisplayAddress> tag and HTML < label> tag.
- public static class HtmlHelpers
- {
-
-
-
-
-
-
-
-
- public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText)
- {
- var builder = new TagBuilder("img");
- builder.MergeAttribute("src", src);
- builder.MergeAttribute("alt", altText);
- return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
- }
-
-
-
- public static MvcHtmlString ActionLinkHtml(this AjaxHelper ajaxHelper, string linkText, string actionName,
- string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
- {
- var repID = Guid.NewGuid().ToString();
- var lnk = ajaxHelper.ActionLink(repID, actionName, controllerName, routeValues, ajaxOptions, htmlAttributes);
- return MvcHtmlString.Create(lnk.ToString().Replace(repID, linkText));
- }
-
-
-
- public static MvcHtmlString ActionLinkSortable(this HtmlHelper helper, string linkText, string actionName,
- string sortField, string currentSort, object currentDesc)
- {
- bool desc = (currentDesc == null) ? false : Convert.ToBoolean(currentDesc);
-
- var routeValues = new System.Web.Routing.RouteValueDictionary();
- routeValues.Add("id", sortField);
- routeValues.Add("desc", (currentSort == sortField) && !desc);
-
- if (currentSort == sortField) linkText = string.Format("{0} <span class='badge'><span class='glyphicon glyphicon-sort-by-attributes{1}'></span></span>", linkText, (desc) ? "-alt" : "");
- TagBuilder tagBuilder = new TagBuilder("a");
- tagBuilder.InnerHtml = linkText;
-
- var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
- var url = urlHelper.Action(actionName, routeValues);
- tagBuilder.MergeAttribute("href", url);
-
- return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
- }
-
-
-
- public static MvcHtmlString DisplayAddressFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
- System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression, bool isEditable = false,
- object htmlAttributes = null)
- {
- var valueGetter = expression.Compile();
- var model = valueGetter(helper.ViewData.Model) as InGaugeService.Address;
- var sb = new List<string>();
- if (model != null)
- {
- if (!string.IsNullOrEmpty(model.AddressLine1)) sb.Add(model.AddressLine1);
- if (!string.IsNullOrEmpty(model.AddressLine2)) sb.Add(model.AddressLine2);
- if (!string.IsNullOrEmpty(model.AddressLine3)) sb.Add(model.AddressLine3);
- if (!string.IsNullOrEmpty(model.City) || !string.IsNullOrEmpty(model.StateRegion) ||
- !string.IsNullOrEmpty(model.PostalCode)) sb.Add(string.Format("{0}, {1} {2}", model.City,
- model.StateRegion, model.PostalCode));
- if (model.IsoCountry != null) sb.Add(model.IsoCountry.CountryName);
- if (model.Latitude != null || model.Longitude != null) sb.Add(string.Format("{0}, {1}",
- model.Latitude, model.Longitude));
- }
-
- var delimeter = (isEditable) ? Environment.NewLine : "<br />";
- var addr = (isEditable) ? new TagBuilder("textarea") : new TagBuilder("address");
- addr.MergeAttributes(new System.Web.Routing.RouteValueDictionary(htmlAttributes));
- addr.InnerHtml = string.Join(delimeter, sb.ToArray());
- return MvcHtmlString.Create(addr.ToString());
- }
- public static string Label(string target, string text)
- {
- return String.Format("<label for='{0}'>{1}</label>", target, text);
- }
-
-
- public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText)
- {
- string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
- return new MvcHtmlString(str);
- }
- }