如何通过外部按钮一次性在数据库中添加jqgrid数据

时间:2015-04-07 19:14:55

标签: c# jquery asp.net asp.net-mvc jqgrid

如何通过我在jqgrid页面中创建的外部按钮在jqgrid中添加值并稍后将其保存在数据库中?

我有以下jqgrid:

<script type="text/javascript">
    ...

    jQuery(#grid-table).jqGrid({
        url: '@Url.Action("GetStore", "Store")',
        datatype: 'json',
        mtype: 'Get',
        height: '430',
        colNames: [ 'Code', 'Name' ],
        colModel: [
            { key: true, name: 'Id', index: 'Id', sorttype: "int" },
            { key: false, name: 'Name', index: 'Name', editable: true }
        ],
        viewrecords: true,
        loadonce: true,
        rowNum: 10,
        rowList: [5, 10, 15],
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false
            Id: "0"
        },
        pager: jQuery(#grid-pager),
        altRows: true,
        multiselect: true,
        multiboxonly: true,
        caption: "Stores",
    });

    jQuery(grid_selector).jqGrid('navGrid', #grid-pager,
        {   //navbar options
            edit: false,
            add: true,
            del: false,
            search: false,
            refresh: false,
            view: false,
        },
        {
            recreateForm: true,
            url: '@Url.Action("Edit","Store")',
        },
        {
            recreateForm: true,
            url: '@Url.Action("Create","Store")',
        },
        {
            recreateForm: true,
            url: '@Url.Action("Delete", "Store")',
        },
        {
            recreateForm: true,
            multipleSearch: true
        },
        {
            recreateForm: true,
        }
    )
</script>

....

<button type="submit" class="btn btn-info" id="subitbutton"> 
    Create 
</button>

我的模型中的以下代码:

[Key]
public int Id { get; set; }

public string Name { get; set; }

我的控制器中的以下代码:

public JsonResult GetStores(string sidx, string sord, int page, int rows, int idStore) 
{
    int pageIndex = page - 1;
    int pageSize = rows;
    var storesResults = db.Stores.Select(
            a => new { a.Id, a.Name });

    int totalRecords = storesResults.Count();
    var totalPages = (int) Math.Ceiling((float) totalRecords / (float) rows);
    if (sord.ToUpper() == "ASC")
    {
        storesResults = storesResults.OrderBy(s => s.Name);
        storesResults = storesResults.Skip(pageIndex * pageSize).Take(pageSize);
    }
    else
    {
        storesResults = storesResults.OrderByDescending(s => s.Name);
        storesResults = storesResults.Skip(pageIndex * pageSize).Take(pageSize);
    }
    var jsonData = new
    {
        total = totalPages, page, records = totalRecords, rows = storesResults
    };
    return Json(jsonData, JsonRequestBehavior.AllowGet);
}

[HttpPost]
public ActionResult Create(Stores store)
{
    db.Store.Add(store);
    return view(store);
}

public ActionResult Edit(Store store)
{
    if (ModelState.isValid)
    {
        db.Entry(store).State = EntityState.Modified;
        db.SaveChanges();
    }
    return View(store);
}

public void Delete(string id)
{
    var ids = id.Split(',');
    foreach (var idStore in ids)
    {
        int storeId = Convert.ToInt32(idStore);
        Store storeToDelete = db.Stores.Find(storeId);
        db.Stores.Remove(storeToDelete);
    }
    db.SaveChanges();
}

现在,我的jqgrid将每个新行发送到服务器,我的方法将其保存在数据库中。 我需要的是在我的视图中存储所有行并一次性将所有行发送到我的服务器 - 可能使用外部按钮?

提前致谢。

更新

根据Oleg的要求,这是我的jqGrid演示:

<script type="text/javascript">
    jQuery(function ($) {
        var grid_selector = "#grid-table-dados-adicionais";
        var pager_selector = "#grid-pager-dados-adicionais";

        //resize to fit page size
        $(window).on('resize.jqGrid', function () {
            $(grid_selector).jqGrid('setGridWidth', $(".page-content").width());
        })
        //resize on sidebar collapse/expand
        var parent_column = $(grid_selector).closest('[class*="col-"]');
        $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
            if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
                setTimeout(function () {
                    $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                }, 0);
            }
        })

        jQuery(grid_selector).jqGrid({
            //direction: "rtl",

            url: '@Url.Action("GetDadosAdicionais", "LojaDadosAdicionais", new { idLoja = @Model.Id })',
            datatype: 'json',
            mtype: 'Get',
            height: '430',
            colNames: [' ',
                       'Id',
                       'Name'
            ],
            colModel: [
                {
                    name: 'myac', index: '', width: 65, fixed: true, sortable: false, resize: false,
                    formatter: 'actions',
                    formatoptions: {
                        keys: true,
                        delOptions: {
                            recreateForm: true,
                            reloadAfterSubmit: false,
                            beforeShowForm: beforeDeleteCallback
                        },
                        editformbutton: true,
                        editOptions:
                        {
                            recreateForm: true,
                            reloadAfterSubmit: false,
                            closeAfterEdit: true,
                            beforeShowForm: beforeEditCallback,
                            closeOnEscape: true
                        }
                    }
                },
                { key: true, hidden: true, name: 'Id', index: 'Id', sorttype: "int", editable: false },
                { key: false, hidden: true, name: 'Name', index: 'Name', sorttype: "int", editable: true },
            ],

            viewrecords: true,
            loadonce: true,
            editurl: "clientArray",
            rowNum: 10,
            rowList: [5, 10, 15],
            jsonReader: {
                root: "rows",
                page: "page",
                total: "total",
                records: "records",
                repeatitems: false,
                Id: "0"
            },
            pager: jQuery(pager_selector),
            altRows: true,
            //toppager: true,
            autowidth: true,
            multiselect: true,
            sortorder: "desc",
            scrollOffset: 0,
            height: "auto",
            //multikey: "ctrlKey",
            multiboxonly: true,
            loadComplete: function () {
                var table = this;
                setTimeout(function () {
                    updateActionIcons(table);
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            },
            caption: "Registration",
        });
        $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

        //switch element when editing inline
        function aceSwitch(cellvalue, options, cell) {
            setTimeout(function () {
                $(cell).find('input[type=checkbox]')
                    .addClass('ace ace-switch ace-switch-5')
                    .after('<span class="lbl"></span>');
            }, 0);
        }

        //navButtons
        jQuery(grid_selector).jqGrid('navGrid', pager_selector,
            {   //navbar options
                edit: true,
                editicon: 'ace-icon fa fa-pencil blue',
                add: true,
                addicon: 'ace-icon fa fa-plus-circle purple',
                del: true,
                delicon: 'ace-icon fa fa-trash-o red',
                search: true,
                searchicon: 'ace-icon fa fa-search orange',
                refresh: true,
                refreshicon: 'ace-icon fa fa-refresh green',
                view: true,
                viewicon: 'ace-icon fa fa-search-plus grey',
            },
            {
                closeOnEscape: true,
                closeAfterEdit: true,
                recreateForm: true,
                reloadAfterSubmit: false,
                width: 500,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_edit_form(form);
                }
            },
            {
                closeOnEscape: true,
                closeAfterAdd: true,
                recreateForm: true,
                reloadAfterSubmit: false,
                width: 500,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                    .wrapInner('<div class="widget-header" />')
                    style_edit_form(form);
                }
            },
            {
                closeOnEscape: true,
                closeAfterDelete: true,
                recreateForm: true,
                reloadAfterSubmit: false,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    if (form.data('styled')) return false;
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_delete_form(form);
                    form.data('styled', true);
                }
            },
            {
                //search form
                recreateForm: true,
                reloadAfterSubmit: false,
                afterShowSearch: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                    style_search_form(form);
                },
                afterRedraw: function () {
                    style_search_filters($(this));
                },
                closeOnEscape: true,
                closeAfterSearch: true,
                multipleSearch: true
            },
            {
                //view record form
                recreateForm: true,
                reloadAfterSubmit: false,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                }
            }
        )

        $.extend($.jgrid.edit, {
            beforeSubmit: function () {
                $(this).jqGrid("setGridParam", { datatype: "json" });
                return [true, "", ""];
            }
        });


        $.extend($.jgrid.add, {
            beforeSubmit: function () {
                $(this).jqGrid("setGridParam", { datatype: "json" });
                return [true, "", ""];
            }
        });

        $('#filterButton').click(function (event) {
            event.preventDefault();

            filterGrid();
        });

        $('#TargetDate').datepicker({
            dateFormat: 'mm/dd/yy'
        });

        function filterGrid() {
            var postDataValues = $("#grid").jqGrid('getGridParam', 'postData');

            // grab all the filter ids and values and add to the post object
            $('.filterItem').each(function (index, item) {
                postDataValues[$(item).attr('id')] = $(item).val();
            });

            $('#grid').jqGrid().setGridParam({ postData: postDataValues, page: 1 }).trigger('reloadGrid');
        }

        function style_edit_form(form) {
            //enable datepicker on "sdate" field and switches for "stock" field
            form.find('input[name=sdate]').datepicker({ format: 'yyyy-mm-dd', autoclose: true })

            form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');

            //update buttons classes
            var buttons = form.next().find('.EditButton .fm-button');
            buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
            buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
            buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')

            buttons = form.next().find('.navButton a');
            buttons.find('.ui-icon').hide();
            buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
            buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
        }

        function style_delete_form(form) {
            var buttons = form.next().find('.EditButton .fm-button');
            buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
            buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
            buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
        }

        function style_search_filters(form) {
            form.find('.delete-rule').val('X');
            form.find('.add-rule').addClass('btn btn-xs btn-primary');
            form.find('.add-group').addClass('btn btn-xs btn-success');
            form.find('.delete-group').addClass('btn btn-xs btn-danger');
        }
        function style_search_form(form) {
            var dialog = form.closest('.ui-jqdialog');
            var buttons = dialog.find('.EditTable')
            buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
            buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
            buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
        }

        function beforeDeleteCallback(e) {
            var form = $(e[0]);
            if (form.data('styled')) return false;

            form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
            style_delete_form(form);

            form.data('styled', true);
        }

        function beforeEditCallback(e) {
            var form = $(e[0]);
            form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
            style_edit_form(form);
        }

        //replace icons with FontAwesome icons like above
        function updatePagerIcons(table) {
            var replacement =
            {
                'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
            };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
        }

        function updateActionIcons(table) {
            var replacement =
            {
                'ui-ace-icon fa fa-pencil': 'ace-icon fa fa-pencil blue',
                'ui-ace-icon fa fa-trash-o': 'ace-icon fa fa-trash-o red',
                'ui-icon-disk': 'ace-icon fa fa-check green',
                'ui-icon-cancel': 'ace-icon fa fa-times red'
            };
            $(table).find('.ui-pg-div span.ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
        }

        function enableTooltips(table) {
            $('.navtable .ui-pg-button').tooltip({ container: 'body' });
            $(table).find('.ui-pg-div').tooltip({ container: 'body' });
        }

        //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

        $(document).one('ajaxloadstart.page', function (e) {
            $(grid_selector).jqGrid('GridUnload');
            $('.ui-jqdialog').remove();
        });

    });
</script>

....

<button type="submit" class="btn btn-info" id="submitbutton"> 
    Create 
</button>

1 个答案:

答案 0 :(得分:3)

如果我正确理解您,您可以使用editurl: "clientArray"进行本地编辑。您使用表单编辑。所以你应该使用jqGrid 4.7或更好的free jqGrid 4.8(或github的最新版本)。

$("#subitbutton").click(function () {
    var localGridData = $("#grid-table").jqGrid("getGridParam", "data");
    $.ajax({
        url: "someServerMethod",
        type: "POST",
        data: JSON.stringify(localGridData),
        dataType: "json"
    })
});

依赖于服务器端的实现,data参数值的格式可以不同。您可以使用data: { gridData: localGridData }或jQuery.ajax的其他选项。