【问题标题】:How to add Values to Add to cart如何将值添加到购物车
【发布时间】:2019-05-04 17:35:09
【问题描述】:

我有一个添加到购物车的部分视图,我需要添加所选商品的价格来计算总价。 我想要做的是,当我单击添加到购物车时,AddtoCart 部分视图会使用新的选定商品价格自行更新。

加入购物车部分视图

@model OnlineShopping.MyViewModel

<div class="alert alert-primary" role="alert">
Added to Cart<br />
Total: 0 @Model.SumVM.ToString()  

我有一个产品表,其中包含产品详细信息(id、价格、详细信息、图像)

产品局部视图

    @model OnlineShopping.MyViewModel

    foreach (Product item in Model.ProductsV)
    {

            <tr>
                <td scope="row"><img src="@Url.Content(@item.ProductImage)" 
             width="150" height="200" /></td>
                <td>
                    @item.ProductName
                    <br />Price : @item.ProductPrice $<br /> 
          @item.ProductDetails
                 </td>
                <td><button  type="button" class="btn-outline-primary">Add 
         to cart </button></td>
            </tr>
    }

加入购物车方法

    public ActionResult AddtoCart(int sum)
    {
        var viewModel = new MyViewModel
        {
            SumVM = SumVM + sum
        };

        return View(viewModel);

我尝试将添加到购物车按钮更改为类似的内容:

  <button  type="submit" value="@item.ProductPrice" class="btn-outline- 
  success" name="sum"  onclick="location.href='@Url.Action("AddtoCart", "Home")'" >Add 
   To cart </button>

但由于“sum”变量的空引用,它无法正常工作。

【问题讨论】:

  • 您没有将 sum 作为所需参数发送到 AddtoCart 方法。您需要在Url.Action 中指定它。像这样的东西:Url.Action("AddtoCart", "Home", new { sum = sumValue });
  • 还是不行

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


【解决方案1】:

我是否认为您想要“将产品添加到购物车”并显示购物车中商品的当前总成本?

您的“添加到购物车按钮”当前将页面提交给控制器(服务器),但没有作为 sum 传递的“值”。

我还接受了这样一个事实,即您的代码中没有“购物车”,只显示运行总数。您如何在购物车中存储 什么 是您对此的决定...我的解决方案基于您提供的信息。

我将有以下(作为基本示例)流程:

  • 页面上显示的产品带有“添加到购物车”按钮
  • 点击“添加到购物车”将产品价格发送到控制器
  • [HttpPost] 表示控制器操作接受产品价格并将价格添加到模型中的当前总价中
  • 返回带有新总数的视图。

我假设“产品”包装在 &lt;form method='post' ...&gt; 标记中。

@model OnlineShopping.MyViewModel
foreach (Product item in Model.ProductsV)
{
        <tr>
            <td scope="row"><img src="@Url.Content(@item.ProductImage)" 
         width="150" height="200" /></td>
            <td>
                @item.ProductName
                <br />Price : @item.ProductPrice $<br /> 
      @item.ProductDetails
             </td>
            <td><button value="150" name="sum"  type="button" class="btn-outline-primary">Add 
     to cart </button></td>
        </tr>
}

(注意添加的valuename 属性)

控制器:

[HttpPost]
public ActionResult AddtoCart(int sum)
{
    var viewModel = new MyViewModel
    {
        SumVM = SumVM + sum
    };

    return View(viewModel);
}

真正的购物车解决方案还有很多需要,但这应该可以解决您的直接问题。您将需要购物车来存储添加的商品的产品 ID,一开始可能会处理 > 1 件商品。

【讨论】:

  • 感谢您的帮助,我会努力解决的,如果可行,会及时通知您。
猜你喜欢
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多