Created
September 22, 2020 15:25
-
-
Save smailliwcs/bed3cd3fb8db5c23a0b3d258ab43b709 to your computer and use it in GitHub Desktop.
Singly rendered content in Razor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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