代码之家  ›  专栏  ›  技术社区  ›  Johan Olsson

用实体框架和ASP.NET MVC在一个页面上更新多个实体(同一类型)的最干净方法是什么?

  •  1
  • Johan Olsson  · 技术社区  · 16 年前

    假设我们有一个/cart/checkout视图,其中列出了购物车中的每个产品,以及一个包含数量的文本框(在我的实际应用程序中,数量超过了数量)。您将如何更新数量?我已经使用了下面的代码,但我正在寻找一种“更干净”的方法。

    视图

    <% int i = 0; foreach(var product in Model.Products) { %>
    <p>
        <%= Html.Encode(product.Name) %>
        <%= Html.TextBox("Quantity[" + i + "]", product.Quantity) %>
    </p>
    <% i++; } >
    

    控制器

    [AcceptVerbs(HttpVerbs.Post)]
    // This would be a better way, but it does not work, any ideas?
    //public ActionResult Checkout([Bind(Include = "ProductID, Quantity")] Product[] products)
    public ActionResult Checkout(int[] productID, int[] Quantity)
    {
        // Get the Product from cartRepository, update Quantity and SaveChanges().
    }
    

    你会怎么解决?

    1 回复  |  直到 16 年前
        1
  •  2
  •   Craig Stuntz    16 年前

    创建编辑模型:

    public class ProductEdit
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public int Quantity { get; set; }
    }
    

    投射到模型上进行显示:

    [AcceptVerbs(HttpVerbs.Get)]
    public Checkout(int cartId) 
    {
        var model = (from c in Repository.Where(c.Id == cartId)
                     from p in c.Products
                     select new ProductEdit
                     { 
                         ProductId = p.ProductId,
                         Name = p.Name,
                         Quantity = p.Quantity
                     }).First();
        return View(model);
    }
    

    表单需要使用特定的名称格式绑定到列表:

    <% int i = 0; foreach(var product in Model.Products) { %>
    <p>
        <%= Html.Hidden(string.Format("products[{0}].ProductId", i), product.ProductId) %>
        <%= Html.Encode(product.Name) %>
        <%= Html.TextBox(string.Format("products[{0}].Quantity", i), product.Quantity) %>
    </p>
    <% i++; } >
    

    在发布时绑定到模型:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CheckOut(int cartId, IEnumerable<ProductEdit> products) 
    {
        // update products repository
    }