购物车-MVC模型绑定遇到的问题

问题描述

MVC模型绑定遇到的问题

在实现购物车时,我的其他功能都可以正常运行,只有更新购物车数量这个功能中Carts绑定不到
视图代码:

@model IEnumerable<MVCShopping.Models.Cart>
@{
    var ajaxOption = new AjaxOptions()
    {
        OnSuccess = "RemoveCartSuccess",
        OnFailure = "RemoveCartFailure",
        Confirm = "您确定要从购物车删除吗?",
        HttpMethod = "Post",
    };
}
@section scripts{
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        function RemoveCartSuccess() {
            alert('移出购物从成功');
            location.reload();
        }
        function RemoveCartFailure(xhr)
        {
            alert('移出购物车失败(Http状态代吗:' + xhr.status);
        }
    </script>
    }

<h2>购物车列表</h2>
@using (Html.BeginForm("UpdateAmount", "Cart"))
{
    <table>
        <tr>
            <th>产品名称</th>
            <th>单价</th>
            <th>数量</th>
            <th>小计</th>
            <th></th>
        </tr>
        @{int subTotal = 0;}
        @foreach (var item in Model)
        {
            subTotal += item.Product.Price * item.Amount;
            var ddlAmountList = new SelectList(Enumerable.Range(1,10),item.Amount);
            @Html.Hidden(item.Product.Id.ToString())
            <tr>
                <td>@Html.DisplayFor(t=>item.Product.Name)</td>
                <td>NT¥@(item.Product.Price)</td>
                <td>@Html.DropDownListFor(t=>item.Amount,ddlAmountList)</td>
                <td>NT¥@(item.Product.Price*item.Amount)</td>
                <td>
                    @Ajax.ActionLink("删除","Remove",new{ProductId=item.Product.Id},ajaxOption)
                </td>
            </tr>
        }
        <tr>
            <th></th>
            <th></th>
            <th>总价</th>
            <th id="subtotal">NT¥ @subTotal</th>
            <th></th>
        </tr>
    </table>
    <p>
        <input type="submit" value="更新数量" />
        <input type="button" value="完成订单" onclick="location.href='@Url.Action("Complete","Order")';" />
    </p>
}

控制器CartControl代码:

 public class CartController : Controller
{
    //非会员也可使用所以购物车保存在Session中
    // 显示当前购物从项目
    MvcShoppingContext db = new MvcShoppingContext();
    List<Cart> Carts
    {
        get {
            if (Session["Carts"] == null)
            {
                Session["Carts"] = new List<Cart>();
            }
            return Session["Carts"] as List<Cart>;
        }
        set { Session["Carts"] = value; }
    }
    public ActionResult Index()
    {
        return View(this.Carts);
    }
    //添加产品项目到购物车,如果没有传入Amount参数则默认购买数量为1
    //因为要通过Ajax调用这个Action,所以可以先标示Post属性
    [HttpPost]
    public ActionResult AddToCart(int ProductId, int Amount = 1)
    {
        var product = db.Products.Find(ProductId);
        //验证产品是否存在
        if (product == null)
            return HttpNotFound();
        var existiongCart = this.Carts.FirstOrDefault(p => p.Product.Id == ProductId);
        if (existiongCart != null)
        {
            existiongCart.Amount += 1;
        }
        else
        {
            this.Carts.Add(new Cart() { Product=product,Amount=Amount});
        }
        return new HttpStatusCodeResult(HttpStatusCode.Created);
    }
    //移出购物从项目
    [HttpPost]
    public ActionResult Remove(int ProductId)
    {
        var existingCart = this.Carts.FirstOrDefault(p => p.Product.Id == ProductId);
        if (existingCart != null)
        {
            this.Carts.Remove(existingCart);
        }
        return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
    }
    //更新数量
    [HttpPost]
    public ActionResult UpdateAmount(IEnumerable<Cart> Carts)
    {
        foreach (var item in Carts)
        {
            var existingCart = this.Carts.FirstOrDefault(p => p.Product.Id == item.Product.Id);
            if (existingCart != null)
            {
                existingCart.Amount = item.Amount;
            }
        }
        return RedirectToAction("Index","Cart");
    }
}

就是最后一个更新数量的方法( public ActionResult UpdateAmount(IEnumerable Carts) )上Carts一直为空绑定不到。这是哪里出了问题呢?

解决方案

@{int subTotal = 0;}
@for (int i = 0; i < Model.Count; i++)
{
subTotal += Model[i].Product.Price * Model[i].Amount;
var ddlAmountList = new SelectList(Enumerable.Range(1, 10), Model[i].Amount);
@Html.HiddenFor(modelItem => modelItem[i].Product.Id)

@Html.DisplayFor(modelItem => Model[i].Product.Name)

¥@(Model[i].Product.Price)

@Html.DropDownListFor(modelItem => Model[i].Amount, ddlAmountList)

@(Model[i].Product.Price * Model[i].Amount)元

@Ajax.ActionLink("删除", "Remove", new { ProductId = Model[i].Product.Id }, ajaxOption)

}
这是我参照数上写的代码,运行正常~你可以参考下!
解决方案二:

请问最终你解决了么?update amount获取到了list结果么?

时间: 2024-09-19 23:58:56

购物车-MVC模型绑定遇到的问题的相关文章

ASP.NET MVC 模型绑定的 6 个建议

原文名称:6 Tips for ASP.NET MVC Model Binding 原文地址:http://odetocode.com/Blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx ASP.NETMVC中的Model Binding使用起来非常简单.你的Action方法需要数据,在传入的HTTP请求中携带着你需要的数据,数据可以在请求的表单数据中,还可能在你的URL地址本身中.通过DefaultM

ASP.NET MVC模型绑定的6个建议,徐汇区网站设计

ASP.NET MVC中的Model Binding使用起来非常简单.你的Action方法需要数据,在传入的HTTP请求中携带着你需要的数据,数据可以在请求的表单数据中,还可能在你的URL地址本身中.通过DefaultModelBinder,可以神奇地将表单中的数据和路由中的数据转换到对象中.Model Binder使得你的控制器代码可以干净地从请求以及关联的环境中分离出来. 这里有一些关于在MVC项目中更好使用Model Binding的建议. Tip#1:最好使用Model Binding而

《Pro ASP.NET MVC 3 Framework》学习笔记之二【领域模型的概念介绍及MVC模型绑定】

接着昨天的笔记: 为第一次的Demo添加动态输出(Dynamic Output) 整个应用程序平台的关键点就是构建动态的输出,在MVC中,构建数据是controller的工作,将数据作为HTML的呈现是View的工作,很明显这里有一个将数据从Controller传递到View的过程.其中的一种方式就是通过ViewBag,ViewBag是Controller基类的一个成员,它是一个动态的对象,我们可以给它赋予任意的属性值,并在View中呈现. 阅读更多

ASP.NET Core MVC/WebAPi 模型绑定探索

前言 相信一直关注我的园友都知道,我写的博文都没有特别枯燥理论性的东西,主要是当每开启一门新的技术之旅时,刚开始就直接去看底层实现原理,第一会感觉索然无味,第二也不明白到底为何要这样做,所以只有当你用到了,你再去看理论性的文章时才会豁然开朗,这是我一直以来学习技术的方法.本文我们来讲解.NET Core中的模型绑定. 话题 在ASP.NET Core之前MVC和Web APi被分开,也就说其请求管道是独立的,而在ASP.NET Core中,WebAPi和MVC的请求管道被合并在一起,当我们建立控

ASP.NET MVC数组模型绑定详解_实用技巧

在ASP.NET MVC中使用Razor语法可以在视图中方便地展示数组,如果要进行数组模型绑定,会遇到索引断裂问题,如下示例: <input type="text" name="[0].Name" /> <input type="text" name="[1].Name" /> <input type="text" name="[2].Name" />

MVC 嵌套模型绑定的问题

问题描述 内容:一个商品里有多张图片,图片有2个信息:名称.描述前台代码:<formaction=""method="post"><inputname="Id"value="1"/><inputname="ProductName"value="产品1"/><inputname="Name"value="图片1&quo

《Pro ASP.NET MVC 3 Framework》学习笔记之三十【模型绑定】

模型绑定(Model Binding)是使用浏览器发起Http请求时的数据创建.NET对象的过程.我们每一次定义带参数的action方法时就已经依靠了模型绑定--这些参数对象是通过模型绑定创建的.这一章会介绍模型绑定的原理以及针对高级使用必要的定制模型绑定的技术. 理解模型绑定(Understanding Model Binding) 想象下我们创建了一个控制器如下: View Code using System; using System.Web.Mvc; using MvcApp.Model

Apache OFBiz源码解读之MVC模型

这篇文章我们来共同探讨一下Apache OFBiz的MVC模型的实现机制. 简介 对于Model-View-Controller的概念此处就不做过多介绍了.如果有想了解的请移步:维基百科.这里我只引用维基百科上关于该item的一张图片,来简单展示一下,这三个component之间的交互机制: OFBiz实现MVC是通过XML来串联这三者之间的依赖关系.这里牵扯到几个关键的XML元素:<request-map />,<view-map />,<handler />.这三个

C# web 开发 MVC 模型数据验证 必填项

问题描述 C# web 开发 MVC 模型数据验证 必填项 问题是: 在开发网站的时候.有一个页面是增加产品和编辑产品共用. 为了在编辑的时候.方便ID的获取.在页面上添加隐藏的绑定模型的控件. 在后台数据验证端.该字段并没有设置必填.而前台页面却提示必填.导致没法进行. input class="input-validation-error" data-val="true" data-val-number="字段 PlaProductId 必须是一个数字