Как получить значение одного поля ввода и отправки с каждым продуктом в базу данных - PullRequest
0 голосов
/ 19 декабря 2018

У меня есть страница, на которой я добавляю один или несколько продуктов (эта часть работает) и их добавление продуктов, включая (Название продукта, Серийный номер, Кол-во) в базу данных.Как вы также видите на скриншотах Screeshots у меня есть одно поле ввода Имя клиента , в котором я хочу получить значение поля ввода имени клиента и отправку каждого продукта в базу данных.

Пример, когда данные вставляются в базу данных:

Имя клиента |Название продукта |Серийный номер |Кол-во

Stackoverflow A 1234 1

Stackoverflow B 4567 2


Но, прямо сейчас, при вставке данных в моей базе данных это выглядит так:

Имя клиента |Название продукта |Серийный номер |Кол-во

ноль A 1234 1

ноль B 4567 2

Если честно, я не знаю, как я могу отправлять значение поля ввода Имя клиента с каждым продуктом, когдаего пытается вставить данные в базу данных.Может кто-нибудь, пожалуйста, помогите мне или направьте меня в правильном направлении!Заранее спасибо:)

Контроллер:

[HttpPost]
public JsonResult ProcessCreateRMA(CreateRMAVM vm)
{
    using (var namespace = new namespace())
    {
        if (vm.vares == null)
        {
            vm.vares = new List<CreateRMAVM.vare>();
        }

        foreach (var item in vm.vares)
        {
            var rmainsert = new RMA_History
            {
                //CustomerName = item.CustomerName,
                ProductName = item.ProductName,
                Serialnumber = item.Serialnumber,
                Qty = item.Qty,

            };

            db.RMA_History.Add(rmainsert);
        }
            db.SaveChanges();
        }

        return Json(vm, JsonRequestBehavior.AllowGet);

    }

JavaScript:

<script>
    $(document).ready(function () {
        //Add input field 
        var i = 0;
        $("#add").click(function (e) {
            i++;
            e.preventDefault();
            $("#tbhold").append('<tr id="row' + i + '"><td><div><input type="text" name="vares[' + i + '].ProductName" id=' + i + ' /></div></td><td><div><input type="text" name="vares[' + i + '].SerialNumber" id=' + i + '/></div></td><td><div style="padding:0" class="col-md-12"><input id="Qty" name="vares[' + i + '].Qty"/></div></td><td><button type="button" class="btn btn-danger btn_remove" id="' + i + '" name="remove"><i class="fa fa-minus-circle" aria-hidden="true"></i>Remove</button></td></tr>');
        });

        //Remove input field 
        $(document).on('click', '.btn_remove', function () {
            var button_id = $(this).attr("id");
            $("#row" + button_id + '').remove();
        });

    //Save to db by click
    $("#submit").click(function (e) {
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: '@Url.Action("ProcessCreateRMA", "User")',
            dataType: 'json',
            data: ($('#add_rma').serialize()),
            success: function (result) {
                console.log(result);
            },
            error: function () {
            console.log('something went wrong - debug it!');
            }
        });
    });

 });
</script>

Просмотр:

<label>Customer Name</label>
<input type="text" name="CustomerName" id="CustomerName">

<form name="add_rma" id="add_rma">
    <table id='tbhold' class="table">
        <thead>
            <tr>
                <th>Product Name </th>
                <th>Serial number</th>
                <th>Qty</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <div>
                        <input type="text" name="vares[0].ProductName" id="ProductName" />
                    </div>

                </td>
                <td>
                    <div>
                        <input type="text" name="vares[0].Serialnumber" id="Serialnumber" />
                    </div>
                </td>
                <td>
                    <div>
                        <input name="vares[0].Qty" id="Qty"/>
                    </div>
                </td>

                <td>
                    <button type="button" name="add" id="add">Add more</button>
                </td>
            </tr>
        </tbody>
    </table>
    <input type="submit" name="submit" id="submit" value="Submit" />
</form>

ViewModel:

public class CreateRMAVM
{
   public List<vare> vares { get; set; }

    public class vare
    {

        public vare()
        {

        }

        public vare(/*string CustomerName*/ string ProductName, string SerialNumber, string Qty)
        {
        }

        //public string CustomerName { get; set; }
        public string ProductName { get; set; }
        public string SerialNumber { get; set; }
        public string Qty { get; set; }
    }
 }

Ответы [ 2 ]

0 голосов
/ 19 декабря 2018
<input type="text" name="CustomerName" id="CustomerName">

не входит в определение вашей формы.Переместите это в форму

0 голосов
/ 19 декабря 2018

Я обновил ваш код для работы.Если вы используете сетку данных, я могу порекомендовать вам использовать один из многочисленных, а не пытаться восстановить его самостоятельно.jqGrid (http://www.trirand.com/blog/) - это популярный

  1. Оставьте CompanyName внутри свою форму

  2. Обновите своймодель как таковая. Я включил клиента в CreateRMAVM и в vare

    public class CreateRMAVM
    {
    public List<vare> vares { get; set; }
    public string CustomerName { get; set; }
    
    public class vare
    {
    
    public vare()
    {
    
    }
    
    public vare(/*string CustomerName*/ string ProductName, string SerialNumber, string Qty)
    {
    }
    
    public string CustomerName { get; set; }
    public string ProductName { get; set; }
    public string SerialNumber { get; set; }
    public string Qty { get; set; }
    }
     }
    
  3. Обновите свой контроллер как таковой.CustomerName заполняется в CreateRMAVM, а затем появляется строка кода для копирования в списки vare

[HttpPost] public JsonResult Create(CreateRMAVM vm) { try { if (vm.CustomerName != null && vm.vares != null) { vm.vares.Select(c => { c.CustomerName = vm.CustomerName; return c; }).ToList(); }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...