如何在.NET Core MVC中通过Ajax打开模态弹窗并无刷新保存数据
Hey there! Let's walk through fixing your code to get that Ajax modal working properly for creating positions without page refreshes. Here's what we need to adjust step by step:
1. Update Your Controller Actions
First, your current Create GET action returns a full View, but we need a partial view to load cleanly into the modal. Also, the POST action shouldn't redirect on success—instead, we'll return a JSON response to let the frontend know it worked, or send back the partial view with validation errors if the model is invalid.
// GET: Positions/Create public IActionResult Create() { // Return a partial view instead of a full view (avoids loading layout into modal) return PartialView(); } // POST: Positions/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("PositionId,PositionName")] Position position) { if (ModelState.IsValid) { _context.Add(position); await _context.SaveChangesAsync(); // Return JSON success response for frontend handling return Json(new { success = true, message = "Position created successfully!" }); } // If invalid, return partial view with model errors to display in the modal return PartialView(position); }
2. Adjust Your View Structure
Your current view includes the entire modal container, which will cause duplication. Let's split this: add the empty modal shell to your main view (like Index.cshtml), and turn Create.cshtml into a partial view that holds only the modal content.
Main View (e.g., Index.cshtml)
Add this empty modal container where you want the modal to appear:
<div class="modal fade" id="add-contact" tabindex="-1" role="dialog" aria-labelledby="addPositionsLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content" id="modal-content"> <!-- Partial view content will load here --> </div> </div> </div>
Partial View (Create.cshtml)
Update it to remove full-view elements and focus on the modal's inner content:
@model Models.Position <div class="modal-header"> <h5 class="modal-title" id="addPositionsLabel">Add positions</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <form id="position-form" asp-action="Create"> <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" /> <div class="form-group"> <label asp-for="PositionName"></label> <input asp-for="PositionName" class="form-control" /> <span asp-validation-for="PositionName" class="text-danger"></span> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary" id="save-position">Save</button> </div>
(We added IDs to the form and save button for easier JavaScript targeting)
3. Add JavaScript for Ajax Handling
Now we need to write scripts to load the modal content, submit the form via Ajax, and update the UI without a page refresh. Add this to your main view's Scripts section:
@section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } <script> // Load modal content when the "Add new Positions" button is clicked $(document).on('click', '[data-toggle="ajax-modal"]', function (e) { e.preventDefault(); // Get the action URL from the button's asp-action attribute var url = $(this).attr('href') || $(this).data('url'); $('#modal-content').load(url, function () { $('#add-contact').modal('show'); }); }); // Handle form submission via Ajax $(document).on('click', '#save-position', function () { var form = $('#position-form'); var formData = form.serialize(); $.ajax({ url: form.attr('action'), type: 'POST', data: formData, success: function (response) { if (response.success) { // Close the modal on success $('#add-contact').modal('hide'); // Optional: Refresh your positions list here (e.g., reload a table) alert(response.message); // Replace with a toast notification for better UX } else { // Replace modal content with the partial view showing validation errors $('#modal-content').html(response); } }, error: function () { alert('An error occurred while saving the position.'); } }); }); // Clear modal content when it's closed to avoid stale data $('#add-contact').on('hidden.bs.modal', function () { $('#modal-content').empty(); }); </script> }
4. Add Model Validation
Don't forget to add validation attributes to your Position model to ensure both frontend and backend validate user input:
public class Position { [Key] public int PositionId { get; set; } [Required(ErrorMessage = "Position name is required")] [StringLength(50, ErrorMessage = "Position name cannot exceed 50 characters")] public string PositionName { get; set; } }
Key Takeaways
- Using
PartialViewensures we don't load the full page layout into the modal. - The Ajax POST returns JSON on success, or the partial view with errors to display validation feedback.
- The JavaScript handles modal loading, form submission, and UI updates without any page refreshes.
- Clearing the modal content on close prevents stale data from appearing in future uses.
That should get your workflow working perfectly—users can open the modal, fill out the form, get real-time validation, and save without ever reloading the page!
内容的提问来源于stack exchange,提问作者 cickness

