oligofren oligofren - 3 months ago 7
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

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

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


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

apr apr
Answer

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])
{
    @content()
    items.Add(key, true);
}
Comments