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

如何在ASP.NET中创建模态表单?ASP MVC模态表单嵌入与AJAX提交问题

Step-by-Step Guide to Integrate Your Form into Bootstrap Modal with AJAX Submission & DataTable Update

I’ll walk you through the exact steps to get your form working in the modal, submit it via AJAX, and update your DataTable without a page refresh. Let’s break this down into manageable parts:


1. Embed Your Form in a Bootstrap Modal (Students View)

First, move your existing form code into a Bootstrap modal in your Students view. I’ll include a complete example with common student fields—adjust to match your actual form:

<!-- Button to trigger the modal -->
<button type="button" class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addStudentModal">
  Add New Student
</button>

<!-- Bootstrap Modal -->
<div class="modal fade" id="addStudentModal" tabindex="-1" aria-labelledby="addStudentModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addStudentModalLabel">Add New Student</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="addStudentForm">
          <!-- Include anti-forgery token (critical for ASP.NET security) -->
          @Html.AntiForgeryToken()
          
          <!-- Your form fields here -->
          <div class="mb-3">
            <label for="FirstName" class="form-label">First Name</label>
            <input type="text" class="form-control" id="FirstName" name="FirstName" required>
          </div>
          <div class="mb-3">
            <label for="LastName" class="form-label">Last Name</label>
            <input type="text" class="form-control" id="LastName" name="LastName" required>
          </div>
          <div class="mb-3">
            <label for="Email" class="form-label">Email</label>
            <input type="email" class="form-control" id="Email" name="Email" required>
          </div>
          <!-- Add any other student fields you need -->
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="submitStudentBtn">Save Student</button>
      </div>
    </div>
  </div>
</div>

2. Implement AJAX Form Submission

Next, add jQuery code to handle the form submission without reloading the page. This will send the form data to your api/students endpoint, handle success/error cases, and update your DataTable.

Add this script at the bottom of your Students view (or in a separate JS file):

$(document).ready(function() {
  // Initialize your DataTable (adjust configuration to match your setup)
  const studentTable = $('#studentsTable').DataTable({
    ajax: {
      url: '/api/students',
      type: 'GET',
      dataSrc: '' // Use this if your API returns an array directly
    },
    columns: [
      { data: 'FirstName' },
      { data: 'LastName' },
      { data: 'Email' },
      // Add other columns (e.g., actions like edit/delete)
      { 
        data: 'Id', 
        render: function(studentId) {
          return `<button class="btn btn-sm btn-danger">Delete</button>`;
        }
      }
    ]
  });

  // Handle form submission when "Save Student" is clicked
  $('#submitStudentBtn').click(function() {
    const form = $('#addStudentForm');
    const formData = form.serialize(); // Convert form fields to URL-encoded string

    $.ajax({
      url: '/api/students',
      type: 'POST',
      data: formData,
      // Include anti-forgery token in headers (matches the token in your form)
      headers: {
        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
      },
      success: function(newStudent) {
        // Success actions: close modal, reset form, update DataTable
        $('#addStudentModal').modal('hide');
        form[0].reset(); // Clear form fields for next use
        
        // Option 1: Reload entire DataTable (simple, but refreshes all data)
        studentTable.ajax.reload();
        
        // Option 2: Add the new row directly (faster, no full reload)
        // studentTable.row.add(newStudent).draw();
      },
      error: function(xhr, status, error) {
        // Show error feedback to the user (customize this as needed)
        alert(`Failed to add student: ${xhr.responseText || error}`);
      }
    });
  });

  // Optional: Reset form when modal is closed
  $('#addStudentModal').on('hidden.bs.modal', function() {
    $('#addStudentForm')[0].reset();
  });
});

3. Ensure Your API Endpoint is Set Up Correctly

Make sure your api/students POST endpoint accepts the form data and returns the newly created student (with its ID). Here’s a sample ASP.NET Web API controller action:

[HttpPost]
[ValidateAntiForgeryToken] // Matches the token we sent in AJAX headers
public IActionResult PostStudent(Student student)
{
  if (!ModelState.IsValid)
  {
    return BadRequest(ModelState); // Return validation errors if any
  }

  // Add student to database
  _context.Students.Add(student);
  _context.SaveChanges();

  // Return the created student (this is what we'll use to update the DataTable)
  return CreatedAtAction(nameof(GetStudent), new { id = student.Id }, student);
}

Key Notes:

  • Anti-Forgery Token: Don’t skip this—it protects your app from cross-site request forgery attacks. The @Html.AntiForgeryToken() in the form and the header in the AJAX request work with the [ValidateAntiForgeryToken] attribute on your API action.
  • DataTable Update: Choose between reloading the entire table (simple, good if data might change frequently) or adding the new row directly (faster, better for single updates).
  • Error Handling: Customize the error alert to match your app’s UI (e.g., use a Bootstrap alert inside the modal instead of a browser alert).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:49:42