Question

I have an MVC application which is supposed to show a Shopping Cart Count on the primary _Layout page. I need to update this value as users add or remove data from their cart. Since these data changes can be done from multiple locations throughout the application, I'm hesitant about putting GetCartCount() calls on each and every controller out there.

I was considering using either a ViewBag or a knockout computed observable to store this value in, but I'm open to any other suggestions.

What is the best way to store & update a single value that will be used on a layout page in an MVC application?

Was it helpful?

Solution

The simplest way would be to put this count variable in the Session and output it directly inside of the _Layout.cshtml using @Session. If you don't want to use session you can put this count variable in the ViewBag with every request, you can set it in the BaseController(if you don't have one just create one and inherit your controllers from it) in OnActionExecuting method and you will avoid duplication.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top