Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 _Layout.cshtml viewmodel

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

like image 960
Simon Martin Avatar asked Apr 10 '13 21:04

Simon Martin


2 Answers

Try adding the following to your cart view:

@{Layout = null;}
like image 175
Justin Helgerson Avatar answered Nov 13 '22 05:11

Justin Helgerson


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);
}
like image 45
AaronLS Avatar answered Nov 13 '22 06:11

AaronLS