2

I'm creating a shopping cart for my project in C# using MVC 4.
I stored 3 values: name, price and description as an array in a session.
When I try to call the Session for a foreach loop, it says
"foreach statement cannot operate on variable of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'" What would I have to change? Any help would be greatly appreciated. Thank you

Courses.cshtml

@model IEnumerable<ANON_Capstone.Models.Course>

@if (!User.Identity.IsAuthenticated)
{
@section featured
{
    <section class="featured">
        <div class="content-wrapper">
            <h2 class="text-center">Please Login or Create an Account to make a Purchase!</h2>
        </div>
    </section>
}
}

<div class="row">
<div class="col-lg-9">
    <h2><strong>Courses</strong></h2><br />
    @foreach (var item in Model)
    {
        <div class="col-md-4 col-xs-6 col-s-8 col-lg-4">
            @using (Html.BeginForm("ShoppingCart", "Home"))
            {
                <img src="~/Images/party.gif" style="width: 175px" class="img-responsive" />
                <h2>@item.className</h2>
                <p>[email protected] -- @item.maxStudent spots left! </p>
                <input type="text" name="product" value="@item.className" hidden="hidden" />
                <input type="text" name="totalPrice" value="@item.classPrice" hidden="hidden"  />
                <input type="text" name="custom" value="@item.ClassID" hidden="hidden" />
                if (User.Identity.IsAuthenticated)
                {
                <input class="btn btn-default" type="submit" name="btnConfirm" value="Add to Shopping Cart" />
                }
            }
            <br />
        </div>
    }
</div>
</div>

HomeController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ANON_Capstone.Models;

namespace ANON_Capstone.Controllers
{
public class HomeController : Controller
{
    private UsersContext db = new UsersContext();

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }

    public ActionResult Courses()
    {

        return View(db.Courses.ToList());

    }

    [HttpPost]
    public ActionResult ShoppingCart()
    {
        return View();
    }

    public ActionResult ShoppingCart(string className, string classPrice, string classDesc)
    {
        String[] cart = { className, classPrice, classDesc };
        Session["Cart"] = cart;
        return View();
    }
}
}

ShoppingCart.cshtml

@{
ViewBag.Title = "ShoppingCart";
}

<h2>ShoppingCart</h2>

@using (Html.BeginForm("ValidateCommand", "PayPal"))
{
var cart = Session["Cart"];
<div class="row">
    <div class="col-lg-9">
        <h2><strong>Courses</strong></h2><br />
        <div class="col-md-4 col-xs-6 col-s-8 col-lg-4">
        @foreach (var item in cart)
        {
            <img src="~/Images/party.gif" style="width: 175px" class="img-responsive" />
            <h2>@item.className</h2>
            <input type="text" name="product" value="@item.className" hidden="hidden" />
            <input type="text" name="totalPrice" value="@item.classPrice" hidden="hidden"  />
            <input type="text" name="custom" value="@item.ClassID" hidden="hidden" />
        }
        <br />
        </div>

    </div>
    <input class="btn btn-default" type="submit" name="btnConfirm" value="Check Out with Paypal" />

</div>
}
6
  • How are you storing cart items in the session in the first place? Is it a list? The error is pretty self explanatory.. you're pulling an object out of the Session.. object isn't IEnumerable.. Commented Nov 19, 2013 at 1:52
  • @SimonWhitehead Hi Simon, I am passing the variables from a model through a controller. The controller takes 3 parameters which are name, price, and desc. I then make a string array of the three objects and store it into Session. Commented Nov 19, 2013 at 1:55
  • If it is a string array.. then you need to cast it back out as one. I'll show you in an answer. Commented Nov 19, 2013 at 1:56
  • What you have is one cart items, but in view you are trying to access it as a collection orders. Commented Nov 19, 2013 at 2:28
  • @evhen14 what would I have to do in order to access it as a collection? do I have to cast the session object as collection? or create multiple session? Commented Nov 19, 2013 at 2:37

4 Answers 4

2

Looks like you want a collection of order items in your cart.

To achieve that do something like

public ActionResult ShoppingCart(string className, string classPrice, string classDesc)
{        
    Session["Cart"] = db.Orders.ToList();
    return View();
}

Then use

var cart = Session["Cart"] as IEnumerable<Order>;

in your View to access those items

Sign up to request clarification or add additional context in comments.

7 Comments

Hi, I tried your method and it worked, but now it appears that I can't retrieve the name, price or the description.
Are you getting some sort or error? This may end up being an unrelated issue.
String[] cart = { className, classPrice, classDesc }; This will not create what you want. It just represents one order in terms of strings. But you need a collection of objects with properties
@evhen14 Sorry, I'm pretty bad with programming and programming terms. What do you mean collection of objects with properties?
@Young-kyuQHan objects that have properties on them
|
1

Since you're storing the cart items as a string array.. you need to cast them back out as one:

var cart = Session["Cart"] as string[];

You can then use it in your foreach, because arrays are enumerable.

However, your code contains things like @item.ClassID.. this makes me assume that the cart items aren't actually a string array.. but a list of objects.

1 Comment

I might have messed up with storing it in the Session. I tried to store it without making it a string array the first time and it gave me an error. So I made the three objects go into an array first, and then made the Session.
1

You need to give the code a specific type to use. By default all session variables are objects. Because you are using var, the compiler is looking at the session variable and, since no cast is done, doesn't know what type to use, so it defaults to a single object. Based on what I see it looks like you have a class such as:

public class CartItem
{
    public string ClassName { get; set; }
    public money ClassPrice { get; set; }
    public int ClassID { get; set; }
}

Where you store CartItem[] in session. In this case, to loop over the items you need to cast the item to CartItem[] when you get it out of session with:

var cart = Session["Cart"] as IEnumerable<CartItem>;

Depending on it's location you may need to include a using statement in your view to reference the namespace holding CartItem.

2 Comments

arrays support IEnumerable<>. So that should be Session["Cart"] as IEnumerable<CartItem>;
@evhen14 you're right. I noticed it in a later answer after I posted this. You can easily use the IEnumerable.
0

I would suggest you make this strongly typed with the CartItem and pass an

    List<CartItem> 

either a strongly typed model with:

return View(new List<CartItem> { item1, item2}); 

and have your view use a model List.

Either this or use the the ViewBag and pass down this strongly typed list.

Once in the view you can define a new variable:

Server:

 ViewBag.Items = new List<CartItem> { item1, item2 }; 

Client:

 List<CartItem> items = ViewBag.Items as List<CartItem>

Comments

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.