8

I want to display a count of selected items on every page in my MVC site. I have a ViewModel that defines the properties I want there

public class CartViewModel
{
    public List<CartItem> CartItems { get; set; }
    public decimal CartTotal { get; set; }
}

a controller that gets the Cart, maps it to the view model and passes that on

public ActionResult GetCartSummary()
{
    var cart = Cart.Instance;
    var viewModel = AutoMapper.Mapper.Map<Cart, CartViewModel>(cart);
    return View(viewModel);
}

and a view for that

@model TheWorkshop.Web.Models.Edit.ShoppingCartViewModel

<h2>Cart Summary</h2>
<span>@Model.CartTotal</span>

and finally in my _Layout.cshtml file

@Html.Action("GetCartSummary", "Cart")

But this gives me

System.StackOverflowException was unhandled

2 Answers 2

6

Try adding the following to your cart view:

@{Layout = null;}
Sign up to request clarification or add additional context in comments.

1 Comment

This works nicely; would never have guessed it was the recursing views
3

Try returning a PartialView instead of View:

public ActionResult GetCartSummary()
{
    var cart = Cart.Instance;
    var viewModel = AutoMapper.Mapper.Map<Cart, CartViewModel>(cart);
    return PartialView(viewModel);
}

4 Comments

This will work as well because PartialView implicitly sets Layout = null.
Someone told me only use a partial view if you need to use it elsewhere. Is this a recommended approach?
You use a PartialView anytime you are nesting a view in another view, because otherwise, you will get all of your layout stuff surrounding where the view is nested. I.e. your header Menus/LOGO will be duplicated and it will look terrible.
Maybe they were thinking of shared views. I keep my View and PartialViews for a controller in the same folder. Except when the PartialView is going to be used elsewhere, then in that case I put them in the Shared Views folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.