title: How to add jqgrid data in database all at once via an external button
body: <p>How can I do to add value in jqgrid and save it later in the database via an external button that I created in my page out of jqgrid?</p>
  
  <p>I have the following jqgrid:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      ...
  
      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,
          }
      )
  &lt;/script&gt;
  
  ....
  
  &lt;button type="submit" class="btn btn-info" id="subitbutton"&gt; 
      Create 
  &lt;/button&gt;
  </code></pre>
  
  <p>And the following code in my Model:</p>
  
  <pre><code>[Key]
  public int Id { get; set; }
  
  public string Name { get; set; }
  </code></pre>
  
  <p>And the following code in my Controller:</p>
  
  <pre><code>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 =&gt; 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 =&gt; s.Name);
          storesResults = storesResults.Skip(pageIndex * pageSize).Take(pageSize);
      }
      else
      {
          storesResults = storesResults.OrderByDescending(s =&gt; 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();
  }
  </code></pre>
  
  <p>Right now, my jqgrid sends each new row to the server and my method saves it in the database.
  What I need is to store all rows in my view and send all at once in a single step to my server - using an external button, maybe?</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong><em>UPDATE</em></strong></p>
  
  <p>As requested by Oleg, here is my jqGrid demo:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      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('&lt;span class="lbl"&gt;&lt;/span&gt;');
              }, 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('&lt;div class="widget-header" /&gt;')
                      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('&lt;div class="widget-header" /&gt;')
                      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('&lt;div class="widget-header" /&gt;')
                      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('&lt;div class="widget-header" /&gt;')
                      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('&lt;div class="widget-header" /&gt;')
                  }
              }
          )
  
          $.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('&lt;span class="lbl"&gt;&lt;/span&gt;');
  
              //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('&lt;i class="ace-icon fa fa-check"&gt;&lt;/i&gt;');
              buttons.eq(1).prepend('&lt;i class="ace-icon fa fa-times"&gt;&lt;/i&gt;')
  
              buttons = form.next().find('.navButton a');
              buttons.find('.ui-icon').hide();
              buttons.eq(0).append('&lt;i class="ace-icon fa fa-chevron-left"&gt;&lt;/i&gt;');
              buttons.eq(1).append('&lt;i class="ace-icon fa fa-chevron-right"&gt;&lt;/i&gt;');
          }
  
          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('&lt;i class="ace-icon fa fa-trash-o"&gt;&lt;/i&gt;');
              buttons.eq(1).addClass('btn-default').prepend('&lt;i class="ace-icon fa fa-times"&gt;&lt;/i&gt;')
          }
  
          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('&lt;div class="widget-header" /&gt;')
              style_delete_form(form);
  
              form.data('styled', true);
          }
  
          function beforeEditCallback(e) {
              var form = $(e[0]);
              form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('&lt;div class="widget-header" /&gt;')
              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) &gt; tbody &gt; tr &gt; .ui-pg-button &gt; .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();
          });
  
      });
  &lt;/script&gt;
  
  ....
  
  &lt;button type="submit" class="btn btn-info" id="submitbutton"&gt; 
      Create 
  &lt;/button&gt;
  </code></pre>