Asp.Net MVC - 插入数据库中多行 [英] Asp.Net MVC - Inserting multiple rows in Database

查看:143
本文介绍了Asp.Net MVC - 插入数据库中多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个电子商务应用程序,现在正在ProductAttributes。我想要处理的大小和颜色和数量attribues。

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

 名称 - 颜色 - 大小 - 数量
T-shirtA - 黑色 - 小 - 5件
T-shirtA - 蓝色 - 中 - 10PC
T-shirtA - 蓝色 - 大 - 4件套

我要他处理上述场景。

  1。产品名称:PRODUCT_ID(PK),名称,价格,描述2. ProductSizes:ProductSize_Id(PK),SizeName3. ProductSizeValues​​:ProductSizeValue_Id(PK),ProductSize_Id(FK),名称4. ProductColors:ProductColor_Id(PK),名称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),数量。

首先,我很困惑,我怎么可以存储颜色和尺寸与数量,然后我安装的 Opencart的并看到他们的DB模式,也没有我上面的表格。

我直接插入一些值到数据库和一切工作正常。获得理想的效果。但很明显,我希望我的用户使用的ViewPage存储这些信息。

我创建了一个视图模型

ProductAttributeViewModel.cs

 公共类ProductAttributesViewModel
{
    公共产品产品{搞定;组; }
    公共ProductAttribute ProductAttribute {搞定;组; }
    公共ProductAttributeValue ProductAttributeValue {搞定;组; }
    公众诠释产品编号{搞定;组; }
    公共字符串名称{;组; }
    [AllowHtml]
    公共字符串描述{搞定;组; }
    公共小数?价格{搞定;组; }
    公众诠释?数量{搞定;组; }
    公共字符串大小{搞定;组; }
    公众诠释股票{搞定;组; }
    公众诠释ProductColorVariantId {搞定;组; }
    公众诠释ProductSizeVariantId {搞定;组; }
    公众诠释ProductSizeVariantValueId {搞定;组; }
    公众诠释ProductAttributeId {搞定;组; }
    公众诠释ProductAttributeValueId {搞定;组; }
}

位指示我必须将数据插入复式表。所以他是我的控制器

  [HttpPost]
    [ValidateAntiForgeryToken]
    公众的ActionResult addProduct命令(ProductAttributesViewModel newRecord)
    {
IEnumerable的< SelectListItem> productsizevariants = db.ProductSizeVariants.Select(C =>新建SelectListItem
        {
            值= c.ProductSizeVariantId.ToString(),
            文字= c.Name        });
        ViewBag.ProductSizeVariantId = productsizevariants;        IEnumerable的< SelectListItem> productsizevariantsvalues​​ = db.ProductSizeVariantValues​​.Select(C =>新建SelectListItem
        {
            值= c.ProductSizeVariantValueId.ToString(),
            文字= c.Name        });
        ViewBag.ProductSizeVariantValueId = productsizevariantsvalues​​;        IEnumerable的< SelectListItem> productcolorvariantsid = db.ProductColorVariants.Select(C =>新建SelectListItem
        {
            值= c.ProductColorVariantId.ToString(),
            文字= c.Name        });
        ViewBag.ProductColorVariantId = productcolorvariantsid;                    变种产品=新产品
                    {
                        名称= newRecord.Name,
                        说明= newRecord.Description,
                        价格= newRecord.Price,
                    };                    VAR productattributes =新ProductAttribute
                    {
                        ProductSizeVariantId = newRecord.ProductSizeVariantId,
                        ProductColorVariantId = newRecord.ProductColorVariantId,
                        产品编号= newRecord.ProductId
                    };                    VAR productattributevalues​​ =新ProductAttributeValue
                    {
                        ProductAttributeId = newRecord.ProductAttributeId,
                        产品编号= newRecord.ProductId,
                        ProductSizeVariantId = newRecord.ProductSizeVariantId,
                        ProductSizeVariantValueId = newRecord.ProductSizeVariantValueId,
                        ProductColorVariantId = newRecord.ProductColorVariantId,
                        数量= newRecord.Stock
                    };                    db.Products.Add(产品);
                    db.ProductAttributes.Add(productattributes);
                    db.ProductAttributeValues​​.Add(productattributevalues​​);
                    db.SaveChanges();
                    返回RedirectToAction(指数,家);
  }

一切是伟大的工作。数据存储与外键和所有值都表所示。现在,我想添加动态文本字段添加尺寸和颜色。

我已经存储在DB颜色和大小,从控制器我这些值传递中的DropDownList和填充它们。

查看

  @model FypStore.ViewModels.ProductAttributesViewModel@using(Html.BeginForm(addProduct命令,商店,FormMethod.Post,新{ENCTYPE =的multipart / form-data的@class =表单水平COL-MD-12,角色=形式 }))
{
< D​​IV CLASS =表单组>
    @ Html.LabelFor(M = GT; m.Name,新{@class =COL-MD-2控制标签,data_val_required =需要})
    < D​​IV CLASS =COL-MD-10>
        @ Html.TextBoxFor(M = GT; m.Name,新{@class =表格控})
        @ Html.ValidationMessageFor(M = GT; m.Name)
    < / DIV>
< / DIV>
< D​​IV CLASS =表单组>
    @ Html.LabelFor(M = GT; m.Description,新{@class =COL-MD-2控制标签})
    < D​​IV CLASS =COL-MD-10>
        @ Html.TextAreaFor(M = GT; m.Description,新{@class =表格控})
    < / DIV>
< / DIV>
< D​​IV CLASS =表单组>
    < D​​IV CLASS =行>         @ * @ Html.LabelFor(M = GT; m.ProductSizeVariantId,新{@class =COL-MD-2控制标签})* @
        < D​​IV CLASS =COL-MD-2控制标签>        < / DIV>
            < D​​IV CLASS =input_fields_wrap>
                <按钮类=add_field_button>添加更多的领域与LT; /按钮>
                < D​​IV CLASS =COL-MD-2>
                    @ Html.DropDownList(ProductSizeVariantId,空,大小,新{@class =控制标签})
                < / DIV>
                < D​​IV CLASS =COL-MD-2>
                    @ Html.DropDownList(ProductSizeVariantValueId,NULL,选择尺寸,新{@class =控制标签})
                < / DIV>
                < D​​IV CLASS =COL-MD-2>
                    @ Html.DropDownList(ProductColorVariantId,NULL,选择颜色,新{@class =控制标签})
                < / DIV>
                < D​​IV CLASS =COL-MD-2>
                    @ Html.TextBoxFor(X => x.Stock,新{@placeholder =数量,@class =表格控})
                < / DIV>
            < / DIV>
    < / DIV>
< / DIV>
< D​​IV CLASS =表单组>
            < D​​IV CLASS =COL-MD-偏移2 COL-MD-10>
                <输入类型=提交级=BTN BTN-默认值=创建产品/>
            < / DIV>
        < / DIV>
        }

下面是在演示我想要实现的。

\r
\r

$('。多领域的方式包装)。每个(函数() {\r
    变量$ =包装$('多领域。,这一点);\r
    $(加场,$(本))。点击(函数(五){\r
        $('。多领域:第一个孩子',$包装).clone(真).appendTo($包装).find(输入)的占位符('数量')专注();\r
    });\r
    $('。多领域卸下摆臂场',$包装)。点击(函数(){\r
        如果($('多领域。',$包装器)。长度大于1)\r
            ('多领域的')。$(本).parent删除();\r
    });\r
});

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/jquery/2.1.1/jquery.min.js\"></script>\r
&LT;形式的作用=形式行动=/ wohoo的方法=POST&GT;\r
  &LT;输入类型=文本占位符=名称NAME =名称&GT;&LT; BR /&GT;\r
  &LT;输入类型=文本占位符=价格NAME =价&GT;&LT; BR /&GT;\r
  &LT;输入类型=文本占位符=说明NAME =描述&GT;&LT; BR /&GT;\r
  &LT;标签&gt;&属性LT; /标签&gt;\r
    &LT; D​​IV CLASS =多场包装&GT;\r
      &LT; D​​IV CLASS =多田&GT;\r
        &LT; D​​IV CLASS =多场&GT;\r
        \r
        &LT;选择&GT;\r
        &LT;选项&GT;绿色&LT; /选项&GT;\r
        &LT;选项&GT;蓝色&LT; /选项&GT;\r
        &LT;选项&GT;黑&LT; /选项&GT;\r
        &LT;选项&GT;紫&LT; /选项&GT;\r
        &LT;选项&GT;白色&LT; /选项&GT;\r
        &LT; /选择&GT;\r
        &LT;选择&GT;\r
        &LT;选项&GT; XS&LT; /选项&GT;\r
        &LT;选项&GT;小&LT; /选项&GT;\r
        &LT;选项&GT;中&LT; /选项&GT;\r
        &LT;选项&gt;轻便&LT; /选项&GT;\r
        &LT;选项&GT; XL&LT; /选项&GT;\r
        &LT; /选择&GT;\r
          &LT;输入类型=文本占位符=量NAME =量&GT;\r
          &LT;按钮式=按钮级=删除字段&GT;删除&LT; /按钮&GT;\r
        &LT; / DIV&GT;\r
      &LT; / DIV&GT;\r
    &LT;按钮式=按钮级=加场&gt;添加场和LT; /按钮&GT;\r
  &LT; / DIV&GT;\r
     &LT;按钮式=按钮&GT;创建产品和LT; /按钮&GT;\r
&LT; /形式为GT;

\r

\r
\r


解决方案

如果我理解你纠正你在你的视图模型具有的属性列表。

所以,如果你想用它来工作,你应该把它列出。

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

  //我把你的列表的所有属性,以单独的模型
公共类AttriduteViewModel
{
    公众诠释ProductColorVariantId {搞定;组; }
    公众诠释ProductSizeVariantId {搞定;组; }
    公众诠释ProductSizeVariantValueId {搞定;组; }
    公众诠释ProductAttributeId {搞定;组; }
    公众诠释ProductAttributeValueId {搞定;组; }
    公众诠释?数量{搞定;组; }
}公共类ProductAttributesViewModel
{
    公共产品产品{搞定;组; }
    公共ProductAttribute ProductAttribute {搞定;组; }
    公共ProductAttributeValue ProductAttributeValue {搞定;组; }
    公众诠释产品编号{搞定;组; }
    公共字符串名称{;组; }
    [AllowHtml]
    公共字符串描述{搞定;组; }
    公共小数?价格{搞定;组; }
    公共字符串大小{搞定;组; }
    公众诠释股票{搞定;组; }
    //注意这条线
    公开名单&LT; AttriduteViewModel&GT; AdditionalAttridutes {搞定;组;}
}

这基本上所有。现在,你应该只为您的 AdditionalAttridutes 右装订。这将是更容易 HtmlHelpers ,使它象 Html.DropDownListFor Html.HiddenFor Html.TextBoxFor 。我只是不能看到它在你的视图。

问题是,如果你创建你的输入 s的助手,他们会马上名称属性和你的模型将正确地绑定在发布即可。

这是你会面对另一件事是动态的在你的例子一样创建新的项目。你应该想想正确的名称属性。我建议你​​检查一下这个问题这个伟大的答案

I'm building an E-Commerce app and now working on ProductAttributes. I want to handle Size and Color and Quantity attribues.

Example T-shirt has multiple colors and sizes with different quantity.

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

I want to handle he above scenario.

Tables

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.

First I was confused about how can I store Colors and Sizes with quantity, then I installed OpenCart and saw their DB Schema and no I've above tables.

I've inserted some values directly into the DB and everything is working fine. Getting the desired results. But obviously I want my user to store these details using ViewPage.

I've created a 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 I have to insert data into mutliple tables. so his is my controller

[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");
  }

Everything is working great. Data is stored in all tables with foreign keys and all values. Now I want to add dynamic text fields for adding Size and Colors.

I've colors and sizes stored in DB and from controller I'm passing those values in dropdownlist and populating them.

View

@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>
        }

Here is the demo what I'm trying to achieve.

$('.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>

解决方案

If I understand you correct you have a list of Attributes in your View Model.

So if you want to work with it you should place it to list.

So you should change your View Model:

//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;}
}

That's basically all. Now you should only make right binding for your AdditionalAttridutes. It will be easier to make it with HtmlHelpers like Html.DropDownListFor, Html.HiddenFor and Html.TextBoxFor. I just can't see it in your View.

The thing is if you create your inputs with Helpers they will get right name Attribute and your model will bind correctly on POST.

Another thing that you will face with is dynamically create new Items like in your example. You should think about right name attribute. I advice you to check this great answer about that problem.

这篇关于Asp.Net MVC - 插入数据库中多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆