0

Goal

As described in the title, I wish to inject some HTML, which loads Google Analytics, which only activates once the user accepted cookies and a specific cookie is set and is true. I followed these answers: Check if Cookie Exists

My try

 @{
       using System.Net.Http;
        if (HttpContext.Current.Response.Cookies.AllKeys.Contains("cookieNameHere"))
        {
            <!-- Global site tag (gtag.js) - Google Analytics -->
            <script async src="https://www.googletagmanager.com/gtag/js?id=idhere"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-codehere');
</script>}}

Errors

It complains about the HttpContext, saying that it's not available in the current context and hence I tried to import it without any avail...

Munchkin
  • 857
  • 5
  • 24
  • 51
  • Avoid accessing `HttpContext` in your Views. Instead your `ViewModel` should be a self-contained object that has all the data necessary for the View to render. – Dai Nov 05 '21 at 13:21
  • If you're using ASP.NET Core then `HttpContext.Current` is _completely wrong_ - where did you get the idea you should use it from? – Dai Nov 05 '21 at 13:22
  • You have applied multiple, and conflicting tags, to your question. Please clarify if you're actually ASP.NET Core or ASP.NET MVC (aka ASP.NET 3.5 or 4.x)? – Dai Nov 05 '21 at 13:22
  • I got this idea from browsing StackOverflow. I removed the MVC tag, I'm using .NET 6, ASP.NET Core – Munchkin Nov 05 '21 at 13:25
  • Please post your `Controller`'s action method, and your `ViewModel` class definition. – Dai Nov 05 '21 at 13:26
  • @Dai I'm afraid none of that exists in my codebase or I'm misunderstanding your request. Please note I am a beginner in ASP.NET Core and C# in general. – Munchkin Nov 05 '21 at 13:28
  • I have an API Controller which appears to be irrelevant to this use case I think. ViewModel doesn't appear even once in my codebase. – Munchkin Nov 05 '21 at 13:29
  • and all of this occurs in a general template `_Layout.cshtml` which injects itself into every page. There is `PageModel` under other pages, but not this one for some reason. a `.cs` ending simply does not exist here – Munchkin Nov 05 '21 at 13:35
  • Nevermind, I figured it out.. – Munchkin Nov 05 '21 at 13:43

1 Answers1

0

Remove the unneeded using and simply use if (Context.Request.Cookies.ContainsKey("cookieNameHere")) :

 @{
        if (Context.Request.Cookies.ContainsKey("cookieNameHere"))
        {
            <!-- Global site tag (gtag.js) - Google Analytics -->
            <script async src="https://www.googletagmanager.com/gtag/js?id=idhere"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-codehere');
</script>}}
Munchkin
  • 857
  • 5
  • 24
  • 51