Monthly Archives: February 2016

ASP.NET MVC HTML Helper: Once

public static HtmlString Once(this HtmlHelper @this, Func<dynamic, HelperResult> template)
{
    string key = "Once";
    ISet<string> cache;
    if (@this.ViewContext.HttpContext.Items.Contains(key))
    {
        cache = (ISet<string>)@this.ViewContext.HttpContext.Items[key];
    }
    else
    {
        cache = new HashSet<string>();
        @this.ViewContext.HttpContext.Items[key] = cache;
    }
    string html = template(null).ToString();
    if (!cache.Contains(html))
    {
        cache.Add(html);
        return new HtmlString(html);
    }
    else
    {
        return null;
    }
}

Usage:

@for (int i = 0; i < 10; i++)
{
    @Html.Once(
        @<script type="text/javascript">
            alert("You will only see this once.");
        </script>);
}