oligofren oligofren - 1 year ago 72
C# Question

Ensure partial is only included once per page

How can I ensure a Partial is only included once per page? I have no control of what will include it, so I need to find some kind of

context to set a
flag that can be checked by the Partial à la

@if( ! MyThreadLocalContext.FooBarTemplateLoaded ) {
MyThreadLocalContext.FooBarTemplateLoaded = true;

If anyone should wonder why I would like to have it only included once, it is a
block that will be injected into the required containers by javascript.

apr apr
Answer Source

You can use HttpContext.Current.Items to store any information with a lifespan of the current request. (ASP.NET is using HttpContext.Current.Items heavily behind the scenes for storing information per request)

Runnable example code

var items = HttpContext.Current.Items;
var key = "YoutubeVideoModalTemplateLoaded";
if (!(items.Contains(key)) || !(bool) items[key])
    items.Add(key, true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download