Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:25
Show Gist options
  • Save smailliwcs/bed3cd3fb8db5c23a0b3d258ab43b709 to your computer and use it in GitHub Desktop.
Save smailliwcs/bed3cd3fb8db5c23a0b3d258ab43b709 to your computer and use it in GitHub Desktop.
Singly rendered content in Razor
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
public static class HtmlHelperExtensions
{
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;
}
}
}
@for (int i = 0; i < 10; i++)
{
@Html.Once(
@<script type="text/javascript">
alert("You will only see this once.");
</script>);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment