Выбранная опция не проходит через JqGrid, используя inline-редактирование - PullRequest
0 голосов
/ 07 января 2020

Мне нужна помощь с сохранением выбранной опции в JqGrid. Я использую встроенное редактирование. Я получил все данные, кроме Coutries.countryName и Cities.cityName (оба варианта выбора), он показывает countryId = 0 и cityId = 0, когда я отлаживаю его, хотя я уже выбрал. Страны и города - это FK для моей таблицы продаж в БД.

Мой вопрос: как мне получить значение выбранного параметра и установить для него значение CountryId и cityId? Я нажал много ссылок, но все еще не могу найти решение. Я попытался сохранить его по отдельности в dataEvents, это сработало, но я не могу заставить работать функцию Add, потому что она все равно передавала бы в контроллер countryId = 0 и cityId = 0.

Ниже приведен мой код для таблицы

<div class="table-responsive">
    <table id="grid_id"></table>
    <div id="pager"></div>
</div>
$(function () {

        $grid = $("#grid_id").jqGrid({
            url: '@Url.Action("DataTableToJsonWithJsonNet")',
            mtype: 'GET',
            datatype: 'json',
            colModel: [
                {
                    name: 'Id',
                    label: 'Id',
                    key:true  //use id from database
                },
                {
                    name: 'Sales_Executive',
                    label: 'Sales Executive',
                    editable: true,
                    edittype: 'text',
                    editrules: { required: true }
                },
                {
                    name: 'Units_Sold',
                    label: 'Units Sold',
                    editable: true,
                    edittype: 'text',
                    formatter:'integer',
                    editrules: { required: true }
                },
                {
                    name: 'Finance_Pen',
                    label: 'Finance Pen',
                    editable: true,
                    edittype: 'text',
                    formatter:'integer',
                    editrules: { required: true }
                },
                {
                    name: 'Product_Pen',
                    label: 'Product Pen',
                    editable: true,
                    edittype: 'text',
                    formatter:'integer',
                    editrules: { required: true }
                },
                {
                    name: 'Total_Income',
                    label: 'Total Income',
                    editable: true,
                    edittype: 'text',
                    formatter:'integer',
                    editrules: { required: true }
                },
                {
                    name: 'IPRU',
                    label: 'IPRU',
                    editable: true,
                    edittype: 'text',
                    formatter:'integer',
                    editrules: { required: true }
                },
                {
                    name: 'Countries.countryName',
                    label: 'Country',
                    editable: true,
                    edittype: 'select',
                    editoptions: {
                        dataInit: function (elem) {
                            var v = $(elem).val(); //current country

                            var cities= $.ajax({
                                url: '@Url.Action("getSelectedCities")',
                                data: { country: v },
                                async: false,
                                success: function (data, result) {
                                    if (!result)
                                        alert('Failure to retrieve the Countries.');
                                }
                            }).responseText;
                            $grid.setColProp('Cities.cityName', { editoptions: { value: cities} }); //set the current country 
                        },
                        dataEvents: [ //to get selected option
                            {
                                type: "change",
                                fn: function (e) {

                                    var v = parseInt($(e.target).val(), 10); //get selected country value

                                    var sc = statesOfCountry.filter(x => x.countryId == v); //will get all the cities based on selected country
                                        var newOptions = '<option role="option"> Select City </option>';                              
                                        for (var i = 0; i < sc.length; i++) {
                                             newOptions += '<option role="option" value="' +
                                                    sc[i].Id + '">' +
                                                    sc[i].Name + '</option>';
                                        }
                                        var row = $(e.target).closest('tr.jqgrow');
                                        var rowId = row.attr('id');
                                    $("select#" + rowId + "_Cities\\.cityName", row[0]).html(newOptions); //replace with new html, the \\ is essential to get the correct id

                                }
                            }
                        ]
                    }
                },
                {
                    name: 'Cities.cityName',
                    label: 'City',
                    editable: true,
                    edittype: 'select',
                    //editoptions: {
                    //    dataEvents: [ //to get selected option
                    //        {
                    //            type: "change",
                    //            fn: function (e) {
                    //                var c = $(this).val(); //get city value
                    //                var id = event.target.id; //get city column row id
                    //                id = id.replace('_Cities.cityName', '');
                    //                var salesId = $("#" + id).closest("tr").children("td:first-child").text();

                    //                //post to ajax, will save the city dropdown only
                    //                $.ajax({
                    //                    type: 'POST',
                    //                    url: 'updateCity',
                    //                    data: { id: salesId, city: c },
                    //                }).done(function (response) {
                    //                    alert('Saved!');
                    //                    //jQuery("#grid_id").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid',[{page:1}]); //reload table to get the recent data from server and direct to first page

                    //                })
                    //            }
                    //        }
                    //    ]
                    //}
                }
            ],
            loadComplete: function() {
                $($grid).setColProp('Countries.countryName', { editoptions: { value: allCountries} });
                $($grid).setColProp('Cities.cityName', { editoptions: { value: allCities} });
            },
            loadonce: true,
            editurl: '/SiteOptions/EditRow',
            caption: 'Dummy Data Table',
            height: 'auto',
            rowNum: 10,
            pager: '#pager',
            styleUI: 'Bootstrap4',
            iconSet: 'Octicons',
            onSelectRow: function (id) {
                if (id && id !== lastSel) {
                    if (lastSel !== -1) {
                        $(this).jqGrid('restoreRow', lastSel);
                        resetCitiesValues();
                    }
                    lastSel = id;
                }
            },
            ondblClickRow: function (id) { //when double click the row
                if (id && id !== lastSel) {
                    $(this).jqGrid('restoreRow', lastSel);
                    lastSel = id;
                }
                resetCitiesValues();
                $(this).jqGrid('editRow', id, {
                    keys: true,
                    aftersavefunc: function () {
                        resetCitiesValues();

                    },
                    afterrestorefunc: function () {
                        resetCitiesValues();
                    }
                });
                return;
            },

        });
        $('#grid_id').navGrid('#pager',
            // the buttons to appear on the toolbar of the grid
            { edit: false, add: true, del: true, search: false, refresh: false, view: false, position: "left", cloneToTop: false},
            {
                // options for the Edit Dialog but since this table is using inline editing, leave it blank
            },
            // options for the Add Dialog
            {

                url: '/SiteOptions/AddRow',
                addCaption: "Add Post",
                addtext: "Add",
                //recreateForm: true,
                closeOnEscape: true,
                closeAfterAdd: true,
                reloadAfterSubmit: true,
                onclickSubmit: function (response, postdata) {
                    //sales = postdata.Sales_Executive;
                    //sold = postdata.Units_Sold;
                    //finance = postdata.Finance_Pen;
                    //product = postdata.Product_Pen;
                    //income = postdata.Total_Income;
                    //ipru = postdata.IPRU;
                    //countryId = postdata["Countries.countryName"];
                    //cityId = postdata["Cities.cityName"];

                    ////post to ajax
                    //$.ajax({
                    //    type: 'POST',
                    //    url: 'AddRow',
                    //    data: { salesEX: sales, unitsSold: sold, financePen: finance, productPen: product, totalIncome: income, ipru: ipru, country: countryId, city: cityId }
                    //}).done(function (response) {
                    //    alert('Added!');
                    //    jQuery("#grid_id").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid',[{page:1}]); //reload table to get the recent data from server and direct to first page
                    //})

                }
            },
            // options for the Delete Dailog
            {
                onclickSubmit: function (response, id) {
                    $.ajax({
                        type: 'POST',
                        url: 'DeleteRow',
                        data: { id: id}
                    }).done(function (response) {
                        alert('Deleted!');
                        jQuery("#grid_id").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid',[{page:1}]); //reload table to get the recent data from server and direct to first page
                    })

                }
            });
    });

Ниже моя модель

public class TestingSalesExecutive
    {
        [Key]
        public int Id { get; set; }
        public string Sales_Executive { get; set; }
        public int Units_Sold { get; set; }
        public int Finance_Pen { get; set; }
        public int Product_Pen { get; set; }
        public int Total_Income { get; set; }
        public int IPRU { get; set; }
        public int cityId { get; set; }
        public int countryId { get; set; }
        [ForeignKey("countryId")]
        virtual public TestingCountries Countries { get; set; }
        [ForeignKey("cityId")]
        virtual public TestingCities Cities { get; set; }
    }
public class TestingCountries
    {
        [Key]
        public int countryId { get; set; }
        public string countryName { get; set; }
    }
public class TestingCities
    {
        [Key]
        public int cityId { get; set; }
        public int countryId { get; set; }
        public string cityName { get; set; }
    }

Надеюсь, кто-то может помочь. Спасибо:)

Привет! Я получил ответ, так что вот мое обновление моего кода. Мне просто нужно добавить extraparam внутри editRow

$(this).jqGrid('editRow', id, {
                    keys: true,
                    aftersavefunc: function () {
                        resetCitiesValues();

                    },
                    afterrestorefunc: function () {
                        resetCitiesValues();
                    },
                    oneditfunc : null,
                    successfunc : null,
                    url : null,
                    extraparam: {
                        countryId: function () { //will get the selected country value and set to countryId
                            var sel_id = $('#grid_id').jqGrid('getGridParam', 'selrow');
                            var valueCountry = $('select#' + sel_id + '_Countries\\.countryName option:selected').val();
                            return valueCountry;
                        },
                        cityId: function () { //will get the selected cities value and set to countryId
                            var sel_id = $('#grid_id').jqGrid('getGridParam', 'selrow');
                            var valueCity = $('select#' + sel_id + '_Cities\\.cityName option:selected').val();
                            return valueCity;
                        }
                    },
                    errorfunc: null,
                    restoreAfterError : true,
                    mtype : "POST"
                });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...