通过AJAX和jQuery提交表单至数据库及.NET Web Forms动态文本框值回传问题
Alright, let's tackle both of your .NET Web Forms AJAX scenarios step by step. I'll break this down into two clear sections to make it easy to follow.
First, we'll set up a server-side WebMethod to handle the form submission, then wire up the front-end jQuery to send the data asynchronously.
Step 1: Add a WebMethod to Your Code-Behind
In your .aspx.cs file, add a static WebMethod (required for AJAX access in Web Forms) with your database insertion logic:
using System.Web.Services; using System.Web.Script.Services; using System.Configuration; using System.Data.SqlClient; public partial class YourPage : System.Web.UI.Page { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string SubmitForm(string firstName, string lastName, string email) { try { // Replace with your actual database connection string and table string connString = ConfigurationManager.ConnectionStrings["YourDbConn"].ConnectionString; using (SqlConnection conn = new SqlConnection(connString)) { string query = "INSERT INTO Users (FirstName, LastName, Email) VALUES (@FirstName, @LastName, @Email)"; using (SqlCommand cmd = new SqlCommand(query, conn)) { cmd.Parameters.AddWithValue("@FirstName", firstName); cmd.Parameters.AddWithValue("@LastName", lastName); cmd.Parameters.AddWithValue("@Email", email); conn.Open(); cmd.ExecuteNonQuery(); } } return "Success: Form submitted successfully!"; } catch (Exception ex) { return $"Error: {ex.Message}"; } } }
Step 2: Front-End jQuery AJAX Code
Assume your form has an ID of #userForm with input fields txtFirstName, txtLastName, and txtEmail:
$(document).ready(function() { $('#userForm').submit(function(e) { e.preventDefault(); // Stop default form postback // Gather form data var formData = { firstName: $('#txtFirstName').val().trim(), lastName: $('#txtLastName').val().trim(), email: $('#txtEmail').val().trim() }; // Send AJAX request $.ajax({ type: "POST", url: "YourPage.aspx/SubmitForm", // Match your page name data: JSON.stringify(formData), contentType: "application/json; charset=utf-8", dataType: "json", beforeSend: function() { // Optional: Disable submit button to prevent duplicates $('#submitBtn').prop('disabled', true).text('Submitting...'); }, success: function(response) { alert(response.d); // .d is .NET's wrapper for WebMethod responses $('#userForm')[0].reset(); // Clear form $('#submitBtn').prop('disabled', false).text('Submit'); }, error: function(xhr, status, error) { alert("Submission failed: " + error); $('#submitBtn').prop('disabled', false).text('Submit'); } }); }); });
Since you already have a GridView (gvAllValues) generating dynamic textboxes, we'll focus on capturing edits and sending updates back to the database.
Step 1: Attach Unique IDs to Dynamic Textboxes
First, make sure each textbox has access to the record's primary key. Do this in the GridView's RowDataBound event:
protected void gvAllValues_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // Get the record's ID from your data source int recordId = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID")); // Find the dynamic textbox (replace "txtValue" with your actual control ID) TextBox txtValue = (TextBox)e.Row.FindControl("txtValue"); // Store the ID in the textbox's data attribute txtValue.Attributes.Add("data-id", recordId.ToString()); } }
Step 2: Front-End jQuery for Edits
Bind a blur event (triggered when the textbox loses focus) to all dynamic textboxes to send updates:
$(document).ready(function() { // Use delegated event binding for dynamically generated elements $('#MainContent_gvAllValues').on('blur', 'input[type="text"]', function() { var $txtBox = $(this); var newValue = $txtBox.val().trim(); var recordId = $txtBox.data('id'); // Get the stored record ID // Basic validation (optional but recommended) if (!newValue) { alert("Value cannot be empty!"); $txtBox.focus(); return; } // Send update request $.ajax({ type: "POST", url: "YourPage.aspx/UpdateValue", data: JSON.stringify({ id: recordId, newValue: newValue }), contentType: "application/json; charset=utf-8", dataType: "json", beforeSend: function() { $txtBox.prop('disabled', true); // Prevent further edits during request }, success: function(response) { alert(response.d); $txtBox.prop('disabled', false); }, error: function(xhr, status, error) { alert("Update failed: " + error); $txtBox.prop('disabled', false); // Optional: Revert to original value if needed // $txtBox.val($txtBox.data('original-value')); } }); }); });
Step 3: Add the Update WebMethod
Back in your code-behind, add the method to handle the update:
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string UpdateValue(int id, string newValue) { try { string connString = ConfigurationManager.ConnectionStrings["YourDbConn"].ConnectionString; using (SqlConnection conn = new SqlConnection(connString)) { // Replace with your table and column names string query = "UPDATE YourTable SET YourColumn = @NewValue WHERE ID = @ID"; using (SqlCommand cmd = new SqlCommand(query, conn)) { cmd.Parameters.AddWithValue("@ID", id); cmd.Parameters.AddWithValue("@NewValue", newValue); conn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); return rowsAffected > 0 ? "Success: Value updated!" : "Info: No record found to update."; } } } catch (Exception ex) { return $"Error: {ex.Message}"; } }
Quick Pro Tips
- Always use parameterized queries to avoid SQL injection (like the examples above).
- The
response.dwrapper is specific to .NET Web Forms WebMethods—don't forget to use it! - For better UX, replace alert boxes with inline status messages instead.
内容的提问来源于stack exchange,提问作者WizCycle

