asp.net mvc 视图中的 C# 复选框事件不在表单内部

C# checkbox event in asp.net mvc view not inside form

所以我有一个项目要使用数据库在用户之间创建一个在线商店(post 产品、购买等),但我被困在购物车视图中:到目前为止,我设法做到了在购物车中显示所有选择的(购买)产品,每个产品旁边都有一个选中的复选框 - 取消选中该复选框将意味着用户不想购买该产品,并且会将其从购物车中删除并返回到首页(所有等待出售的产品都在这里)。

产品型号:

public class Product
{
    public int ProductID { get; set; }

    public int OwnerID { get; set; } //the guy who posted the product

    public int? UserID { get; set; } //if someone added the product to his cart, and if the checkbox is unchecked it will be null again and removed from cart

    [Required]
    [Display(Name = "Title")]
    public string Title { get; set; } //name of product

    [Display(Name = "Short Description")]
    public string ShortDescription { get; set; }

    [DataType(DataType.MultilineText)]
    [Display(Name = "Long Description")]
    public string LongDescription { get; set; }

    public DateTime UploadDate { get; set; }

    [DataType(DataType.Currency)]
    [Required]
    [Display(Name = "Price")]
    public decimal Price { get; set; }

    public int State { get; set; } //if the item was bought
}

购物车视图:

@model IEnumerable<MyFirstProject.Models.Product>

@{
    ViewBag.Title = "ShoppingCart";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Your Shopping Cart</h2>

@if (Model == null)
{
    <div style="float:left">Your cart is empty.</div>
    <div>
        Total payment: 0
    </div>
}
else
{
    decimal tPrice = 0;
    <table style="float:left">
        @foreach (var product in Model)
        {
            tPrice = tPrice + product.Price;                
            @Html.Partial("ProductLine", product)            
        }
    </table>
    <div>
        Total payment: @tPrice
    </div>
}

购物车中行的部分视图:

@model MyFirstProject.Models.Product

<tr>
    <td>        
        <input checked="checked" data-val="true" data-val-number="@Model.UserID" @*failed attempt to understand it*@
               id="UserID" name="UserID" type="checkbox" value="true"> @Model.Title        
    </td>        
    <td>           
         @Model.Price.ToString()
    </td>    
</tr>

我的控制器(相关代码):

using MyFirstProject.Models;
using MyFirstProject.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyFirstProject.Controllers
{
    public class ShoppingController : Controller
    {
        private ShopContext db = new ShopContext();

        // GET: User
        public ActionResult Index(Product product=null)
        {
            List<Product> tempList = new List<Product>();
            if (product != null)
            {
                foreach (var p in db.Products.ToList())
                {
                    if (p.ProductID == product.ProductID)
                    {
                        p.UserID = 0;
                        db.SaveChanges();
                        break;
                    }
                }
            }
            foreach(var p in db.Products.ToList())
            {
                if (p.UserID == null || p.State == 1)
                {
                    tempList.Add(p);
                }
            }
            return View(tempList.ToList());
        }


        public ActionResult ShoppingCart()
        {
            List<Product> toCart = new List<Product>();
            foreach (var product in db.Products.ToList())
            {
                if (product.UserID == 0)
                {
                    toCart.Add(product);
                }
            }
            return View(toCart.ToList());
        }        
    }
}

长话短说 - 如何在不在表单内的复选框事件中更改数据库中的参数?

您唯一需要在复选框的数据属性中保留的是产品 ID(或特定产品的唯一 ID + 尺寸 + 颜色组合)

<td>        
   <input checked="checked" class="cartItem" data-productId="@Model.ProductID "
                                  type="checkbox" value="true" > 
   @Model.Title        
</td>  

现在在 javascript 中,我们将监听复选框的 change 事件并向服务器发出 ajax 调用以将其删除。我们将使用 jQuery 来执行此操作。

$(function(){
  $(".cartItem).change(function(e){
     var _this=$(this);
     var productId=_this.data("productId");
     $.post("@Url.Action("RemoveItem","Cart")?productId="+productId,function(re){

         //redirect now
         window.location.href="@Url.Action("Index","Cart")";
     });
  });

});

假设您在 CartController 中有一个名为 RemoveItem 的操作方法,它接受 productId 并从购物车中删除产品。

[HttpPost]
public ActionResult RemoveItem(int productId)
{
  // to do :Remove from cart
  return Json(new { status="success"});
}