【问题标题】:foreach loop with Session in C# using MVC 4使用 MVC 4 在 C# 中使用 Session 进行 foreach 循环
【发布时间】:2013-12-02 10:05:00
【问题描述】:

我正在使用 MVC 4 在 C# 中为我的项目创建一个购物车。
我在会话中存储了 3 个值:名称、价格和描述作为数组。
当我尝试为 foreach 循环调用 Session 时,它说
“foreach 语句不能对 'object' 类型的变量进行操作,因为 'object' 不包含 'GetEnumerator' 的公共定义” 我必须改变什么? 任何帮助将不胜感激。 谢谢

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>$@item.classPrice -- @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>
}

【问题讨论】:

  • 首先您是如何在会话中存储购物车项目的?是清单吗?这个错误很容易解释..你从会话中拉出一个object..object不是IEnumerable..
  • @SimonWhitehead 嗨,西蒙,我正在通过控制器传递模型中的变量。控制器采用 3 个参数,即名称、价格和描述。然后,我创建了三个对象的字符串数组并将其存储到 Session 中。
  • 如果它是一个字符串数组..那么你需要把它作为一个来投射。我会在答案中告诉你。
  • 您拥有的是一个购物车项目,但鉴于您正试图将其作为收集订单访问。
  • @evhen14 我必须做什么才能将其作为集合访问?我必须将会话对象转换为集合吗?还是创建多个会话?

标签: c# asp.net-mvc-4 session foreach


【解决方案1】:

您似乎想要购物车中的订单商品集合。

要实现这一点,请执行以下操作

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

然后使用

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

在您的视图中访问这些项目

【讨论】:

  • 您好,我尝试了您的方法并且成功了,但现在我似乎无法检索名称、价格或描述。
  • 您是否遇到了某种错误或错误?这可能最终成为一个不相关的问题。
  • String[] 购物车 = { className, classPrice, classDesc };这不会创造你想要的东西。它仅代表字符串的一种顺序。但是你需要一组具有属性的对象
  • @evhen14 对不起,我对编程和编程术语很不了解。什么是具有属性的对象集合?
  • @Young-kyuQHan 具有属性的对象
【解决方案2】:

您需要为代码提供特定类型以供使用。默认情况下,所有会话变量都是对象。因为您使用的是 var,所以编译器正在查看会话变量,并且由于没有进行强制转换,因此不知道要使用什么类型,因此它默认为单个对象。根据我所见,您似乎有一个课程,例如:

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

您在会话中存储 CartItem[] 的位置。在这种情况下,要遍历项目,您需要在退出会话时将项目转换为 CartItem[]:

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

根据它的位置,您可能需要在视图中包含 using 语句来引用包含 CartItem 的命名空间。

【讨论】:

  • 数组支持 IEnumerable。所以应该是 Session["Cart"] as IEnumerable;
  • @evhen14 你是对的。我在发布此内容后在稍后的答案中注意到了这一点。您可以轻松使用 IEnumerable。
【解决方案3】:

由于您将购物车项目存储为一个字符串数组.. 您需要将它们转换为一个:

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

然后您可以在 foreach 中使用它,因为数组是可枚举的。

但是,您的代码包含 @item.ClassID.. 之类的内容,这让我假设购物车项目实际上不是字符串数组.. 而是对象列表。

【讨论】:

  • 我可能搞砸了将它存储在 Session 中。我第一次尝试存储它而不将其设为字符串数组,但它给了我一个错误。所以我先把这三个对象做成了一个数组,然后做成了Session。
【解决方案4】:

我建议你使用 CartItem 进行强类型化并传递一个

    List<CartItem> 

强类型模型:

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

并让您的视图使用模型列表。

要么使用这个,要么使用 ViewBag 并传递这个强类型列表。

在视图中您可以定义一个新变量:

服务器:

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

客户:

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

【讨论】:

    猜你喜欢
    • 2016-07-11
    • 2013-07-16
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多