【问题标题】:Asp.Net MVC - Inserting multiple rows in DatabaseAsp.Net MVC - 在数据库中插入多行
【发布时间】:2016-04-25 23:16:14
【问题描述】:

我正在构建一个电子商务应用程序,现在正在研究 ProductAttributes。我想处理尺寸、颜色和数量属性。

示例 T恤有多种颜色和尺寸,数量不同。

 Name    - Color - Size  - Qty
T-shirtA - Black - Small - 5pc
T-shirtA - Blue - Medium - 10pc
T-shirtA - Blue - Large -  4pc

我想处理他上面的场景。

表格

1. Product: Product_Id(pk), Name, Price, Description

2. ProductSizes: ProductSize_Id(pk), SizeName

3. ProductSizeValues: ProductSizeValue_Id(pk), ProductSize_Id(fk), Name

4. ProductColors: ProductColor_Id(pk), Name

5. ProductAttribues: ProductAttribute_Id(pk), ProductSize_Id(fk), ProductColor_Id(fk)

6. ProductAttribueValues: ProductAttributeValue_Id(pk), ProductAttribute_Id(fk), Product_Id(fk), ProductSizeValue_Id(fk), ProductColor_Id(fk), Quantity.

首先我对如何存储颜色和尺寸以及数量感到困惑,然后我安装了 OpenCart 并看到了他们的数据库架构,但我没有上面的表格。

我已将一些值直接插入数据库,一切正常。得到想要的结果。但显然我希望我的用户使用 ViewPage 存储这些详细信息。

我创建了一个 ViewModel

ProductAttributeViewModel.cs

public class ProductAttributesViewModel
{
    public Product Product { get; set; }
    public ProductAttribute ProductAttribute { get; set; }
    public ProductAttributeValue ProductAttributeValue { get; set; }
    public int ProductId { get; set; }
    public string Name { get; set; }
    [AllowHtml]
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public int? Quantity { get; set; }
    public string Sizes { get; set; }
    public int Stock { get; set; }
    public int ProductColorVariantId { get; set; }
    public int ProductSizeVariantId { get; set; }
    public int ProductSizeVariantValueId { get; set; }
    public int ProductAttributeId { get; set; }
    public int ProductAttributeValueId { get; set; }
}

Contoller 我必须将数据插入到多个表中。所以他是我的控制器

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AddProduct(ProductAttributesViewModel newRecord)
    {
IEnumerable<SelectListItem> productsizevariants = db.ProductSizeVariants.Select(c => new SelectListItem
        {
            Value = c.ProductSizeVariantId.ToString(),
            Text = c.Name

        });
        ViewBag.ProductSizeVariantId = productsizevariants;

        IEnumerable<SelectListItem> productsizevariantsvalues = db.ProductSizeVariantValues.Select(c => new SelectListItem
        {
            Value = c.ProductSizeVariantValueId.ToString(),
            Text = c.Name

        });
        ViewBag.ProductSizeVariantValueId = productsizevariantsvalues;

        IEnumerable<SelectListItem> productcolorvariantsid = db.ProductColorVariants.Select(c => new SelectListItem
        {
            Value = c.ProductColorVariantId.ToString(),
            Text = c.Name

        });
        ViewBag.ProductColorVariantId = productcolorvariantsid;

                    var product = new Product
                    {
                        Name = newRecord.Name,
                        Description = newRecord.Description,
                        Price = newRecord.Price,
                    };

                    var productattributes = new ProductAttribute
                    {
                        ProductSizeVariantId = newRecord.ProductSizeVariantId,
                        ProductColorVariantId = newRecord.ProductColorVariantId,
                        ProductId = newRecord.ProductId
                    };

                    var productattributevalues = new ProductAttributeValue
                    {
                        ProductAttributeId = newRecord.ProductAttributeId,
                        ProductId = newRecord.ProductId,
                        ProductSizeVariantId = newRecord.ProductSizeVariantId,
                        ProductSizeVariantValueId = newRecord.ProductSizeVariantValueId,
                        ProductColorVariantId = newRecord.ProductColorVariantId,
                        Quantity = newRecord.Stock
                    };

                    db.Products.Add(product);
                    db.ProductAttributes.Add(productattributes);
                    db.ProductAttributeValues.Add(productattributevalues);
                    db.SaveChanges();
                    return RedirectToAction("Index", "Home");
  }

一切都很好。数据存储在具有外键和所有值的所有表中。现在我想添加动态文本字段以添加大小和颜色。

我将颜色和大小存储在 DB 中,并且从控制器中我将这些值传递到下拉列表中并填充它们。

查看

@model FypStore.ViewModels.ProductAttributesViewModel

@using (Html.BeginForm("AddProduct", "Store", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal col-md-12", role = "form" }))
{
<div class="form-group">
    @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label", data_val_required = "required" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Name)
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Description, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    <div class="row">

         @*@Html.LabelFor(m => m.ProductSizeVariantId, new { @class = "col-md-2 control-label" })*@
        <div class="col-md-2 control-label">

        </div>
            <div class="input_fields_wrap">
                <button class="add_field_button">Add More Fields</button>
                <div class="col-md-2">
                    @Html.DropDownList("ProductSizeVariantId", null, "Size", new { @class = "control-label" })
                </div>
                <div class="col-md-2">
                    @Html.DropDownList("ProductSizeVariantValueId", null, "Select Size", new { @class = "control-label" })
                </div>
                <div class="col-md-2">
                    @Html.DropDownList("ProductColorVariantId", null, "Select Color", new { @class = "control-label" })
                </div>
                <div class="col-md-2">
                    @Html.TextBoxFor(x => x.Stock, new { @placeholder = "Quantity", @class = "form-control" })
                </div>
            </div>
    </div>
</div>
<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-default" value="Create Product" />
            </div>
        </div>
        }

这是我想要实现的演示

$('.multi-field-wrapper').each(function() {
    var $wrapper = $('.multi-fields', this);
    $(".add-field", $(this)).click(function(e) {
        $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').placeholder('quantity').focus();
    });
    $('.multi-field .remove-field', $wrapper).click(function() {
        if ($('.multi-field', $wrapper).length > 1)
            $(this).parent('.multi-field').remove();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" action="/wohoo" method="POST">
  <input type="text" placeholder="Name" name="name"><br />
  <input type="text" placeholder="Price" name="price"><br />
  <input type="text" placeholder="Description" name="description"><br />
  <label>Attributes</label>
    <div class="multi-field-wrapper">
      <div class="multi-fields">
        <div class="multi-field">
        
        <select>
        <option>Green</option>
        <option>Blue</option>
        <option>Black</option>
        <option>Purple</option>
        <option>White</option>
        </select>
        <select>
        <option>XS</option>
        <option>Small</option>
        <option>Medium</option>
        <option>Large</option>
        <option>XL</option>
        </select>
          <input type="text" placeholder="quantity" name="quantity">
          <button type="button" class="remove-field">Remove</button>
        </div>
      </div>
    <button type="button" class="add-field">Add field</button>
  </div>
     <button type="button">Create Product</button>
</form>

【问题讨论】:

    标签: c# mysql asp.net asp.net-mvc


    【解决方案1】:

    如果我理解你是正确的,你的视图模型中有一个属性列表。

    所以如果你想使用它,你应该把它放在列表中。

    所以你应该改变你的视图模型:

    //I put all properties of your list to separate model
    public class AttriduteViewModel
    {
        public int ProductColorVariantId { get; set; }
        public int ProductSizeVariantId { get; set; }
        public int ProductSizeVariantValueId { get; set; }
        public int ProductAttributeId { get; set; }
        public int ProductAttributeValueId { get; set; }
        public int? Quantity { get; set; }
    }
    
    public class ProductAttributesViewModel
    {
        public Product Product { get; set; }
        public ProductAttribute ProductAttribute { get; set; }
        public ProductAttributeValue ProductAttributeValue { get; set; }
        public int ProductId { get; set; }
        public string Name { get; set; }
        [AllowHtml]
        public string Description { get; set; }
        public decimal? Price { get; set; }
        public string Sizes { get; set; }
        public int Stock { get; set; }
        //note this line
        public List<AttriduteViewModel> AdditionalAttridutes {get; set;}
    }
    

    基本上就是这样。现在您应该只为您的AdditionalAttridutes 进行正确绑定。使用HtmlHelpers(如Html.DropDownListForHtml.HiddenForHtml.TextBoxFor)会更容易。我只是在你的视图中看不到它。

    问题是,如果您使用 Helpers 创建 inputs,他们将获得正确的 name 属性,并且您的模型将在 POST 上正确绑定。

    您将面临的另一件事是像您的示例中那样动态创建新项目。您应该考虑正确的名称属性。我建议您检查 this great answer 关于该问题。

    【讨论】:

    • 我猜在AttributeViewModel 中也会有ProductIdQuantity
    • @user3223395667 这取决于您的实现。但是你应该是Quantity。我的坏
    • 你最后给出的链接我没有完全理解,虽然它帮助我理解了一点。我有 4 5 个表,你能发布控制器的示例代码吗?我通过ProductAttributeViewModel。既然你已经切片了视图模型,我现在应该通过什么?我还是有点困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    相关资源
    最近更新 更多