If you are looking to set the value of the cookies across all the controllers, you can use action filters and apply them on controllers. Action filters contain logic that will be implemented before or after a controller action is executed. They can be applied to an individual action method or the entire controller.
I will give you an overview of how your ActionFilterAttribute class could look like and explain each step along the way. You can find screenshot examples below.
Overview of an ActionFilterAttribute Class
- Create a public class named UserCookieFilter that inherits from ActionFilterAttribute
- Override the OnActionExecuting method
- OnActionExecuting method is one of the four overload methods in the ActionFilterAttribute that will be called “before” the controller is called. It takes an ActionExecutingContext as its parameter.
- Pass that filter context into the base OnActionExecuting method
- Set the default value of the cookie
- Create conditions to modify the value of the cookies accordingly
- Add the value of the cookie to the filter context
- Apply the filter to the controller
You can now apply the UserCookieFilter attribute to the controller and your cookies will be passed along to the view.
<input type="hidden" id="buttonInfo" value="@Response.Cookies["adminAccess"].Value" /> <script> var buttonInfo = document.getElementById('buttonInfo').value; </script>