You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap 4表单验证后通过POST请求跳转至ASPX页面实现数据存储

How to Submit Bootstrap 4 Validated Form to ASPX Page via POST

Hey there! Since you're new to Bootstrap 4 and JavaScript, let's break this down simply — I've handled this exact scenario before, so here's how to get your form submitting to your ASPX backend after validating successfully:

Step 1: Update Your Form HTML

First, make sure your form has the right attributes to know where to send data, plus unique identifiers for easy JavaScript targeting. Add the action (pointing to your ASPX processing page), method="POST", and an id to grab it in JS. Also, ensure all form fields have a name attribute — this is how your ASPX backend will read the submitted values!

<form class="needs-validation" id="submitForm" action="YourProcessingPage.aspx" method="POST" novalidate>
  <!-- Example form field (repeat for all your inputs) -->
  <div class="form-group">
    <label for="username">用户名</label>
    <input type="text" class="form-control" id="username" name="username" required>
    <div class="invalid-feedback">请输入用户名</div>
  </div>

  <!-- Submit button -->
  <button class="btn btn-primary" type="submit">提交表单</button>
</form>

Step 2: Modify the Bootstrap Validation Script

The default Bootstrap validation script stops form submission if fields are invalid, but doesn't handle valid submissions beyond adding the validation class. We'll tweak it to either let the form submit normally (with page refresh) or use AJAX (no page refresh) — pick whichever fits your needs!

Option 1: Traditional Form Submission (Page Redirect)

This is the simplest approach. We'll only block submission when validation fails; when it passes, the form will send data to your ASPX page automatically.

(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Grab our form by ID
    const form = document.getElementById('submitForm');

    form.addEventListener('submit', function(event) {
      // Check if form is valid
      if (!form.checkValidity()) {
        // Block submission if invalid
        event.preventDefault();
        event.stopPropagation();
      }
      // Add Bootstrap's validation styles regardless
      form.classList.add('was-validated');
    }, false);
  }, false);
})();

Option 2: AJAX Submission (No Page Refresh)

If you want to submit data without reloading the page (and show success/error messages dynamically), use this version. We'll prevent default submission, send data via fetch(), and handle the backend response.

(function() {
  'use strict';
  window.addEventListener('load', function() {
    const form = document.getElementById('submitForm');

    form.addEventListener('submit', function(event) {
      event.preventDefault(); // Always block default submission for AJAX
      
      if (form.checkValidity()) {
        // Validation passed — prepare form data
        const formData = new FormData(form);
        
        // Send POST request to ASPX page
        fetch('YourProcessingPage.aspx', {
          method: 'POST',
          body: formData
        })
        .then(response => {
          if (response.ok) {
            return response.text(); // Or parse JSON if your backend returns it
          }
          throw new Error('Network response was not ok.');
        })
        .then(data => {
          // Handle success — show a message, reset form, etc.
          alert('表单提交成功!');
          form.reset();
          form.classList.remove('was-validated');
          // Optional: Redirect to a success page
          // window.location.href = 'Success.aspx';
        })
        .catch(error => {
          // Handle errors
          console.error('提交出错:', error);
          alert('提交失败,请稍后重试。');
        });
      }
      
      // Add validation styles
      form.classList.add('was-validated');
    }, false);
  }, false);
})();

Step 3: Set Up Your ASPX Backend

In your YourProcessingPage.aspx.cs file, read the form data and save it to your database. Here's a quick example:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.HttpMethod == "POST")
    {
        // Get form values using the "name" attribute of your inputs
        string username = Request.Form["username"];
        // Repeat for other fields...
        
        // Save to database (replace with your actual DB logic)
        // Example using SQL:
        // string query = "INSERT INTO Users (Username) VALUES (@Username)";
        // using (SqlConnection conn = new SqlConnection(yourConnectionString))
        // {
        //     SqlCommand cmd = new SqlCommand(query, conn);
        //     cmd.Parameters.AddWithValue("@Username", username);
        //     conn.Open();
        //     cmd.ExecuteNonQuery();
        // }
        
        // Optional: Return a success message for AJAX requests
        Response.Write("Success");
        Response.End();
    }
}

Key Notes

  • Don't forget the novalidate attribute on your form — it disables browser default validation so Bootstrap's custom styles work properly.
  • All form fields must have a name attribute; without it, your ASPX backend can't read the submitted values.
  • For security, always sanitize user input before saving to your database to prevent SQL injection attacks.

内容的提问来源于stack exchange,提问作者Brandon168

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:23:18