Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a cookie value in an ASP.NET Core MVC Razor view

I set a cookie using JavaScript when the user clicks a button:

document.cookie = "menuSize=Large";

I need to access this cookie in razor syntax so I can output the correct styles at the top of _Layout.cshtml every time the user changes pages:

    @{
        if (cookie == "Large")
        {
            <style>
LARGE STYLES
            </style>
        }
        else
        {
            <style>
SMALL STYLES
            </style>
        }
    }
like image 880
Blake Rivell Avatar asked Aug 02 '17 05:08

Blake Rivell


People also ask

How does MVC get cookies from client?

In ASP.Net MVC application, a Cookie is created by sending the Cookie to Browser through Response collection (Response. Cookies) while the Cookie is accessed (read) from the Browser using the Request collection (Request. Cookies).

Does ASP NET MVC use razor pages?

A Razor Page is almost the same as ASP.NET MVC's view component. It has basically the syntax and functionality same as MVC. The basic difference between Razor pages and MVC is that the model and controller code is also added within the Razor Page itself. You do not need to add code separately.

What is razor view in ASP NET MVC?

Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.


1 Answers

I was having the same problem and did it:

@using Microsoft.AspNetCore.Http;

@{

    if (HttpContext.Request.Cookies["menuSize"].Value == "Large")
    {
        <style>
            LARGE STYLES
        </style>
    }

}
like image 102
Caio M. Avatar answered Sep 22 '22 14:09

Caio M.