JavaScript - Поместите массивы в модель представления, затем верните модель через AJAX - PullRequest
1 голос
/ 06 августа 2020

У меня есть массивы, созданные в моем javascript, например, вот как создается один массив

  $("button").click(function () {
                //var token = $("input[name='__RequestVerificationToken']", "#__AjaxAntiForgeryForm").val();
                var partArray = []; //for creating json array                
                //looping through trs with class tr_clonePart
                $(".tr_clonePart").each(function () {
                    //for storing qtys and radios of cloned and original
                    var qty_actiontype_cloned = []
                    var datas_cloned = {};
                    var data_original = {}//fro original
                    var qty_actiontype_original = [];
                    //get infos for various fields
                    var p_id = $(this).find("td > a").attr('p-id');
                    var mfg = $(this).find("input.part_mfg").val();
                    var part_name = $(this).find("input.part_name").val();
                    var qty_in_item = $(this).find("input.qty_in_item").val();
                    var item = {};
                    //add values in json objects
                    item["PartID"] = p_id
                    item["MFGNumber"] = mfg
                    item["PartName"] = part_name
                    item["QtyInItem"] = qty_in_item
                    //chcking if part-class is checked or not
                    if ($(this).find("input[type='checkbox'].part-class").is(':checked')) {

                        var move_all = $(this).find("input[type='checkbox'].part-class").val();
                        //item["MoveAll"] = move_all
                        item["MoveAll"] = (move_all == "true");
                        var radios = $(this).find("input[type='radio'].radios:checked").val();
                        data_original["action_type"] = radios //adding value of radios in array
                        //item['radios_c'] = radios_c
                        var qty = $(this).find("input.qty").val();
                        data_original["qty"] = qty //adding value of qty in array
                        qty_actiontype_original.push(data_original)
                        item["QtyActionTypeOriginal"] = qty_actiontype_original
                        //item["qty"] = qtys
                    } else {
                        var qty = $(this).find("input.qty").val();
                        //for original data
                        data_original["qty"] = qty
                        var radios = $(this).find("input[type='radio'].radios:checked").val();
                        //for original data
                        data_original["action_type"] = radios
                        qty_actiontype_original.push(data_original)
                        item["QtyActionTypeOriginal"] = qty_actiontype_original
                        //item["MoveAll"] = "false"
                        item["MoveAll"] = (move_all == "false");
                        //looping through cloned trs
                        $(".tr_clonePart_" + p_id).each(function () {

                            var radios_clones = $(this).find("input[type='radio'].radios:checked").val();
                            //puuting value in cloned array
                            datas_cloned["action_type"] = radios_clones

                            console.log(radios_clones)
                            var qty_clones = $(this).find("input.qty").val();

                            datas_cloned["qty"] = qty_clones
                            //push data in cloned array
                            qty_actiontype_cloned.push(datas_cloned)

                        });
                        //push array in cloned json object
                        item["QtyActionTypeCloned"] = qty_actiontype_cloned


                    }
                    //getting other values
                    var onHand = $(this).find("input.OnHand").val();
                    var onWorkOrder = $(this).find("input.onWorkOrder").val();
                    var committed = $(this).find("input.committed").val();
                    var fstk = $(this).find("input.fstk").val();
                    item["OnHand"] = onHand
                    item["OnWorkOrder"] = onWorkOrder
                    item["Committed"] = committed
                    item["FSTK"] = fstk
                    //push json object in array
                    partArray.push(item)

                })

Но я хочу иметь возможность поместить 'partArray' в мою модель itemViewModel, которая выглядит вот так

 public class ItemViewModel
    {
        [Required]
        public int Id { get; set; }
        [Required]
        public int JobId { get; set; }
        public string ItemId { get; set; }
        public string ItemName { get; set; }
        public string MFGNumber { get; set; }
        public IList<ItemPartViewModel> Parts { get; set; }
        public IList<ItemComponentViewModel> Components{ get; set; }
        public IList<ComponentPartViewModel> ComponentParts { get; set; }
        public IList<ComponentSubCompViewModel> ComponentSubComps { get; set; }
        public IList<SubCompPartViewModel> SubCompParts { get; set; }

        public IList<SubCompSubCompViewModel> SubCompSubComps { get; set; }
        public IList<SubCompSubCompPartViewModel> SubCompSubCompParts { get; set; }

    }

, если это поможет, вот мой макет itemPartViewModel (все остальные IList имеют тот же макет)

 public class ItemPartViewModel
    {
        [Required]
        public int ID { get; set; }
        public int ItemID { get; set; }
        public string PartID { get; set; }
        public string MFGNumber { get; set; }
        public string PartName { get; set; }
        public float QtyInItem { get; set; }
        public float Qty { get; set; }
        public bool MoveAll { get; set; }
        public float OnHand { get; set; }
        public float OnWorkOrder { get; set; }
        public float Committed { get; set; }
        public float FSTK { get; set; }

        public QtyActionTypeCloned[] qty_actiontype_cloned { get; set; }
        public QtyActionTypeOriginal[] qty_actiontype_original { get; set; }

        // This is the additional property to contain what user picks
        public PartActionType SelectedActionType { get; set; }
    }

Итак, мне интересно, как я могу разместить каждый массив, который создается, в мою itemViewModel, а затем передаю всю ViewModel в метод контроллера?

Вот мой AJAX

  $.ajax({
                    type: "POST",
                    url: "@IGT.baseUrl/JODetails/SpecialOrderSelection",
                    contentType: "application/json; charset=utf-8",
                    data:
                        JSON.stringify({ itemViewModel: myData }),
                    dataType: "json",
                    traditional: true,
                    success: function () {
                        alert('Success!');
                    },
                    error: function () {
                        alert('Error! ');
                    }
                });

Возможно ли это и как это можно сделать?

1 Ответ

0 голосов
/ 06 августа 2020

Это предположение, но не будет ли

var myData = {
    Id: idValue,
    JobId: jobIdValue,
    ItemId: itemIdValue,
    ItemName: itemNameValue,
    MFGNumber: mfgNumberValue,
    Parts: partArray,
    Components: componentArray,
    ComponentParts: componentPartArray,
    ComponentSubComps: componentSubCompsArray,
    SubCompParts: subCompPartsArray,
    SubCompSubComps: subCompSubCompsArray,
    SubCompSubCompParts:subCompSubCompPartsArray
}


var ajaxData = JSON.stringify({myViewModel: myData});

Тогда метод post в контроллере

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SpecialOrderSelection(ItemViewModel myViewModel)
    {
        //rest of post method 
    }

Также на клиенте qty_actiontype_cloned и qty_actiontype_original являются массивами . Поэтому я предлагаю в вашем ItemPartViewModel изменить

public QtyActionTypeCloned qty_actiontype_cloned { get; set; }
public QtyActionTypeOriginal qty_actiontype_original { get; set; }    

на

public QtyActionTypeCloned[] qty_actiontype_cloned { get; set; }
public QtyActionTypeOriginal[] qty_actiontype_original { get; set; }

Также похоже, что имена ваших клиентов не совпадают с именами серверов. Чтобы исправить это, вам нужно либо изменить на клиенте, т.е.

item["QtyActionTypeOriginal"] = qty_actiontype_original

должен стать

item["qty_actiontype_original"] = qty_actiontype_original

, либо на сервере, т.е.

public QtyActionTypeOriginal[] qty_actiontype_original { get; set; }

должен стать

public QtyActionTypeOriginal[] QtyActionTypeOriginal{ get; set; }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...