如何修改jQuery代码实现两个GridView数据插入SQL Server
Solution to Support Multiple GridViews in jQuery Data Insert
First off, let's fix the critical issues in your HTML markup first—duplicate IDs will break your jQuery selectors and cause unexpected behavior:
Corrected HTML Markup
<div> <div id="dgvGrid1"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"> <HeaderStyle BackColor="#ffbf00" /> <Columns> <asp:BoundField DataField="Question" HeaderText="Q" HeaderStyle-Width="50%"></asp:BoundField> <asp:BoundField DataField="Tim" HeaderText="Tim Answer" HeaderStyle-Width="8%"></asp:BoundField> <asp:BoundField DataField="Tom" HeaderText="Tom Answer" HeaderStyle-Width="8%"></asp:BoundField> </Columns> </asp:GridView> <!-- Use class for buttons + data attribute to link to target GridView --> <input class="btn-save-grid" type="button" value="Save Row Data" data-grid-id="GridView1" /> </div> </div> <div> <div id="dgvGrid2"> <!-- Fix duplicate GridView ID --> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false"> <HeaderStyle BackColor="#ffbf00" /> <Columns> <asp:BoundField DataField="Question" HeaderText="Q" HeaderStyle-Width="50%"></asp:BoundField> <asp:BoundField DataField="Tim" HeaderText="Tim Answer" HeaderStyle-Width="8%"></asp:BoundField> <asp:BoundField DataField="Tom" HeaderText="Tom Answer" HeaderStyle-Width="8%"></asp:BoundField> </Columns> </asp:GridView> <input class="btn-save-grid" type="button" value="Save Row Data" data-grid-id="GridView2" /> </div> </div>
Modified jQuery Code (Supports Both GridViews)
<script> // Reusable function to collect data from a specific GridView function collectGridViewData(gridSelector) { var qnaList = []; $(gridSelector).find('tr:has(td)').each(function () { var $row = $(this); var qnaItem = {}; // Adjust this selector if your row identifier (checkbox) is in a different position var rowType = $row.find('input[type="checkbox"]').val(); if ($row.find('input[type="checkbox"]').is(':checked')) { switch(rowType) { case 'Q': qnaItem.Q = $row.find("td:nth-child(1)").html(); break; case 'tim': qnaItem.Tim = $row.find("td:nth-child(1)").html(); break; case 'Tom': qnaItem.Tom = $row.find("td:nth-child(1)").html(); break; } // Only add valid items to the list if (Object.keys(qnaItem).length > 0) { qnaList.push(qnaItem); } } }); return qnaList; } // Bind click event to all save buttons $(".btn-save-grid").click(function () { var $btn = $(this); // Get the target GridView ID from the button's data attribute var targetGridId = $btn.data('grid-id'); var gridSelector = '[id*=' + targetGridId + ']'; // Collect data from the specific GridView var qnaData = collectGridViewData(gridSelector); console.log("Collected data for " + targetGridId + ":", qnaData); if (qnaData.length > 0) { // Replace f2/f3 with your actual values var f2 = "your-f2-value"; var f3 = "your-f3-value"; $.ajax({ type: 'POST', url: '<%= ResolveUrl("About.aspx/SaveGridViewRowData") %>', data: JSON.stringify({ qna: qnaData, f2: f2, f3: f3, // Optional: send grid identifier to backend if you need to distinguish sources sourceGrid: targetGridId }), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { console.log("Save successful:", response); // Add custom success logic (e.g., alert, refresh grid) }, error: function (xhr, status, error) { console.error("Save failed:", error); // Add custom error handling } }); } else { console.log("No selected rows to save for " + targetGridId); // Optional: alert the user no rows were selected } }); </script>
Key Improvements & Explanations
- Reusable Data Collection: The
collectGridViewDatafunction abstracts row data gathering, so you can use it for any GridView without rewriting logic. - Class-Based Event Binding: Using a class (
btn-save-grid) for all save buttons avoids duplicate ID issues, and thedata-grid-idattribute clearly links each button to its target GridView. - Targeted Data Gathering: When a button is clicked, we only collect data from its associated GridView—no cross-contamination between GridView1 and GridView2.
- Fixed Data Structure: Corrected the original code's confusion between arrays and objects, ensuring
qnaDatais always a valid array of row objects. - Cleaner AJAX Payload: Using
JSON.stringifyto build the request body eliminates manual string-concatenation errors.
Optional Backend Note
If you need to handle data differently based on which GridView it comes from, add a sourceGrid parameter to your SaveGridViewRowData method in the C# backend to receive the identifier.
内容的提问来源于stack exchange,提问作者BoJack Horseman
相关产品推荐
相关产品推荐

