首页 > 解决方案 > 如何在模型到模型中使用 jquery 发送数据和图像。?

问题描述

我想将 Model.Images 中的价格、名称 ID 和第一张图片发送到我的购物车控制器,但它不起作用我的 Model.Images 中有 3 张图片告诉我如何解决这个问题。

总结控制器

public IActionResult Summery(int id)
        {
            MobileModel m = new MobileHandler().GetMobile(id).ToModel();         
            return View(m);      
        }

数据传入的 MobileModel 类表单

 public class MobileModel
    {
        public MobileModel()
        {
            Images = new List<string>();
        }
        public int Id { get; set; }

        public string Name { get; set; }

        public int Price  { get; set; }
        public List<string> Images { get; set; }
}

总结视图

@{
@model MobileModel
}
<button type="submit" class="addcartbtn mt-5" data-pid="@Model.Id" data-pname="@Model.Name" data-pprice="@Model.Price" data-purl="@Model.Images[0]" data-pqty="1">
    <span class=" fa fa-shopping-cart"> Add To Cart</span>
</button>

jQuery代码

    $(".addcartbtn").click(function (e) {
        e.preventDefault();

        var obj = {
            "Id": $(this).data("pid"),
            "Name": $(this).data("pname"),
            "Price": $(this).data("pprice"),
            "Images": $(this).data("purl"),
            "Quantity": $(this).data("pqty")
        }
        $(this).parents("#proditem").fadeOut(300);
        $.ajax(
            {
                url: "/Cart/Add",
                type: "GET",
                data:  obj
            }
        ).done(function (itemscount) {
            $("#cartitems").text(itemscount);
    });

CartModel 类

public class ShoppingCartItem
{

        public int Id { get; set; }
        public string Name  { get; set; }
        public int Price { get; set; }
        public string Images { get; set; }
        public int Quantity { get; set; }
        public int Amount { 
            get {
                return Quantity * Price;
                } 
        }
}

我要发送数据的购物车控制器

 public class CartController : Controller
    {
        [HttpGet]
        public int Add(ShoppingCartItem item)
        {
            ShoppingCart cart = HttpContext.Session.Get<ShoppingCart>(WebUtil.Cart);
            if (cart == null) cart = new ShoppingCart();
            cart.Add(item);
            HttpContext.Session.Set(WebUtil.Cart, cart);            
            return cart.NumberOfItems;
        }

标签: c#jqueryasp.net-coremodel-view-controller

解决方案


推荐阅读