I have a Shopping Basket which holds selected items by the user and is stored in a session variable. I’d like this to show various values on every view about the basket state i.e. basket:1, but I can only see how to pass this to a view at a single entry point. How would I initialise every view with this List?
Share
You could render a
child actionin your Layout. The idea of a child action is that it could execute some logic in parallel to the main action.For example you could have the following controller:
and then you will have a corresponding partial view (
~/Views/ShoppingBasketInfo/Index.cshtml):and then you could find an appropriate place in your Layout to render this action:
Now all your views will have this information shown at the specified location without worrying about where this information is coming from, how is it stored or what view model it uses. The main actions are completely independent.
I have decorated the child action with the
[ChildActionOnly]attribute to ensure that this action will never be accessible through a normal HTTP request from the client using for example/ShoppingBasketInfo/Index. It could only be used within the context of the main executing action.