Lessons in this course (9)

4. MVC 5: custom HTML helpers, display/editor templates and child actions

Intermediate★ Must knowLesson 4 of 9
csharp
public static class HtmlHelperExtensions
{
    // Simple helper
    public static MvcHtmlString Money(this HtmlHelper html, decimal amount, string culture = "en-IN")
    {
        var tag = new TagBuilder("span");
        tag.AddCssClass(amount < 0 ? "money negative" : "money");
        tag.SetInnerText(amount.ToString("C", CultureInfo.GetCultureInfo(culture)));   // encodes text
        return MvcHtmlString.Create(tag.ToString());
    }

    // Strongly typed helper with an expression (like TextBoxFor)
    public static MvcHtmlString RatingFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, int>> expr, int max = 5)
    {
        var name = ExpressionHelper.GetExpressionText(expr);
        var value = (int)(ModelMetadata.FromLambdaExpression(expr, html.ViewData).Model ?? 0);
        var sb = new StringBuilder("<span class=\"rating\">");
        for (int i = 1; i <= max; i++)
            sb.Append($"<label><input type=\"radio\" name=\"{HttpUtility.HtmlAttributeEncode(name)}\" value=\"{i}\" {(i == value ? "checked" : "")}/>★</label>");
        return MvcHtmlString.Create(sb.Append("</span>").ToString());
    }
}
cshtml
@Html.Money(Model.Total)
@Html.RatingFor(m => m.Stars)

Register the namespace in Views/web.config (<add namespace="Shop.Web.Helpers" />) so all views see it.

Razor @helper (MVC 5 only) — inline helpers in App_Code/Helpers.cshtml. Display/editor templates — Views/Shared/DisplayTemplates/Money.cshtml used by Html.DisplayFor(m => m.Price) when the property has [UIHint("Money")] or matches the type name. Child actions (Html.Action) for self-contained widgets with their own data.