【问题标题】:C# MVC simple cart based on session基于会话的 C# MVC 简单购物车
【发布时间】:2016-03-20 23:08:06
【问题描述】:

我正在尝试找出在会话中存储产品的简单购物车。

索引视图:

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.product1)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.product1)
        </td>
        <td>
            @Html.ActionLink("Add products to cart", "AddToBasket", new { id=item.id})
        </td>
    </tr>
}

</table>

每个产品旁边是“添加到购物车”到控制器中的 AddToBasket 方法,该方法读取产品的 id 并将其存储在 session["basket"] 列表中:

public ActionResult AddToBasket(int? id)
{
        if (Session["Basket"] == null)
        {
            Session["Basket"] = new List<int>();
        }

        ((List<int>)Session["Basket"]).Add(id.Value);
        ViewBag.List = Session["Basket"];


        return RedirectToAction("Index");
}

现在我将产品的 ID 存储在会话中,并希望从数据库中检索信息并将它们与 ID 匹配。这是我无法弄清楚的。 我试图创建字典并用值填充它,但显然这不起作用:

public ActionResult ShowBasket()
{
    List<int> lista = new List<int>((List<int>)Session["Basket"]);

    Dictionary<int, string> productSet = new Dictionary<int, string>();

    foreach (var product in lista)
    {
        productSet[product] = db.products.Find(product).ToString();
    }

    ViewBag.products = productSet;

    return View(slownik);
}

也尝试通过 ADO.Net 从数据库中检索数据但再次失败:

public ActionResult ShowBasket()
{
    List<int> plist = new List<int>((List<int>)Session["Basket"]);

    SqlConnection myConnection = new SqlConnection(my_connection_string);
    SqlCommand myCommand;
    SqlDataReader myReader;
    string s;

    myConnection.Open();
    s = "select product from db.products where id=" + plist[0];
    myCommand = new SqlCommand(s, myConnection);
    myReader = myCommand.ExecuteReader();
    if (myReader.Read())
    {
        string loaded_record = myReader.GetString("product1");
    }

    myConnection.Close();
    return View();
}

有人可以帮忙吗? 我只是初学者,经过数十个小时寻找想法后,我决定寻求帮助,因为我无法做到......

您的帮助将不胜感激!

【问题讨论】:

  • 尝试使用实体框架而不是使用 ADO.Net,虽然起初它可能是一个不寻常的概念,但您基本上有一个代表您的表的对象结构。从那里编写简单的查询将在后台编译成 SQL 并执行,您将获得作为强类型对象的结果。以这种方式工作要简单得多,而且不易出错。查看上面的代码,可能存在几个问题,从您编写的手动查询,到 Session 中的值如何存储或使用 Session 初始化后您在 plist 中得到什么。
  • 你能解释一下这段代码吗: Dictionary productSet = new Dictionary(); foreach (var product in productSet) {...} 你新建一个空字典,然后在 foreach 中使用
  • 当你说“这不起作用”时,你能说得更具体些吗?
  • Artsion,我复制的时候出错了。在 foreach 循环中,我使用存储在会话中的列表并尝试填充字典。
  • db.products.Find(product).ToString();可能 ToString() 方法在这里不适合。如果 db.products.Find(product) 从数据库返回对象,您应该指定正确的属性名称。例如,db.products.Find(product).ProductName

标签: c# asp.net-mvc session model-view-controller


【解决方案1】:

目前还不是很清楚你的问题是什么/在哪里。但是,在我看来,您从未将更新的项目列表分配回会话。

在下面的代码中,我特别指出会话应该更新为更新后的列表。

public ActionResult AddToBasket(int? id)
{
    if (Session["Basket"] == null)
    {
        Session["Basket"] = new List<int>();
    }

    var items = (List<int>)Session["Basket"];
    items.Add(id.Value);
    Session["Basket"] = items;
    ViewBag.List = Session["Basket"];

    return RedirectToAction("Index");
}

您的代码还有其他问题可以在Code Review 上找到帮助,请务必先阅读tour。在 Stack Overflow,我们专门查看错误。

【讨论】:

  • @Ashley_Medway 感谢您指出代码审查。下次我会记住的。你说得对,我正在寻找如何做某事的想法,而不是在代码中出现错误。
  • @berabazoo 他们将帮助您提供最佳实践等,但他们确实有一套严格的规则:)
【解决方案2】:

我无法完全理解您要达到的目的,另外我们缺少一些有关显示购物车内容的视图的信息,但我会尽力帮助您。

此解决方案适用于实体框架,并且可以轻松扩展到 ADO.NET。我做了一些修改,希望对您即将进行的项目有所帮助。

ADO 版本:

public ActionResult ShowBasketADO()
    {
        List<Product> result = new List<Product>();

        List<int> plist = new List<int>((List<int>)Session["Basket"]);
        //We try to be sure that we only make a single query
        string query = "select id, descripcion from products where id in (" + string.Join(",", plist) + ")";
        //Start using IDisposable interface (yes, you can also use it for SqlCommand)
        using (SqlConnection myConnection = new SqlConnection(cnxString))
        {
            SqlCommand myCommand;
            SqlDataReader myReader;
            myConnection.Open();
            myCommand = new SqlCommand(query, myConnection);
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {
                Product item = new Product();
                item.Id = (int)myReader[0];
                item.Descripcion = (string)myReader[1];
                result.Add(item);
            }
            myConnection.Close();
        }

        return View(result);
    }

EF 解决方案:

private ApplicationDbContext db = new ApplicationDbContext();
    public ActionResult ShowBasket()
    {

        List<int> mylist = new List<int>((List<int>)Session["Basket"]);

        List<Product> IntheCart = new List<Product>();

        foreach (var item in mylist)
        {
            IntheCart.Add(db.Productos.Find(item));

        }
       return View(IntheCart);
      }

以及渲染它的代码:

@model IEnumerable<TestApp.Models.Product>
@{
    ViewBag.Title = "ShowBasket";
}
<h2>ShowBasket</h2>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Descripcion)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Descripcion)
        </td>
        <td>
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}
</table>

如果您还有其他问题,请告诉我。

另外,请查看此Link 以获取完整教程

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 2020-06-16
    • 2012-03-11
    相关资源
    最近更新 更多