Accessing another model without changing the controller

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
1 anno tempo fa
I'm having some products with a max. quantity of one per shopping cart. Instead of showing the warning when a user clicks "add to cart" when there is already 1 of these products, I'd like to redirect to the shopping cart.

To do so I'm modifying the _AddToCart.cshtml view but unfortunately the model "AddToCart" doesn't know how many products are in the shopping cart. This info is in another model. I try to avoid to change controller code since it would make upgrade to new versions more complicated in the future.

How can I access this data without changing the controller code?
1 anno tempo fa
If you want to " avoid to change controller code", then I think there are two options:
1) create a plugin that implements an action filter  (this is old, but probably still applies)
2) "resolve" a service in the .cshtml file, and call appropriate method
1 anno tempo fa
Hi NY,

Thanks for your reply. I've tried to inject the service and that worked. Many thanks!
Here is what I've done:


@inject IShoppingCartModelFactory shoppingCartServce
...

                    var shoppingCartModel = await shoppingCartServce.PrepareMiniShoppingCartModelAsync();

                    if(shoppingCartModel.Items.Count == 0)
                    {
                        => Normal button

                    }
                    else
                    {
                        => Link with "href="@Url.RouteUrl("ShoppingCart")"
                    }
...
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.