Rules

Secret ingredients to quality software

Edit
Info

Do you use Html Helpers and Partial Views to simplify Views?

Created on 07 Mar 2013 | Last updated by Tiago Araujo on 07 Mar 2013 06:50 PM (about 8 years ago)

Repeated sections of User Interface should be encapsulated in either Html Helpers or Partial Views to avoid repetition.

<div class="featured">
    @if (ViewData.ContainsKey("FeaturedProduct"))
    {
        <span class="ProductName">@ViewBag.FeaturedProduct.Name</span>
        <span class="ProductPrice">@ViewBag.FeaturedProduct.Price</span>
    }
</div>

Figure: Bad Example – The above code could be encapsulated into a Partial View for reuse

public static class DateExtensions
{
    public static MvcHtmlString GetTodayDate(this System.Web.Mvc.HtmlHelper helper)
    {
        return new MvcHtmlString(DateTime.Now.ToShortDateString());
    }
}
@Html.GetTodayDate()

Figure: Good Example – Using an HTML Helper extension method for reusable code

@Html.Partial("_FeaturedProduct")

Figure: Good Example – Using a Partial View for reusable sections of UI

Damian BradyDamian Brady

We open source. This page is on GitHub