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

如何在ASP.NET Core Create控制器动作中触发Sweet Alert弹窗

Hey there! Glad the previous solution worked for you. Let's tackle this SweetAlert issue in your ASP.NET Core Create action—here's exactly what's going wrong and how to fix it:

Why Your Current Code Isn't Triggering the Popup

The problem is your form is doing a synchronous submit by default. As soon as you click "Create", the browser sends the form data to the server and refreshes the page immediately—your SweetAlert code never gets a chance to run before the page reloads.

The Fix: Use AJAX for Asynchronous Form Submission

By submitting the form via AJAX, we keep the page from refreshing, let the server process the request, then trigger the SweetAlert once we get a success response. Here's how to set it up step by step:

Step 1: Update Your Create View (Razor)

First, give your form a unique ID so we can target it with JavaScript, and make sure all form fields have proper name attributes (they should if you're using tag helpers):

<form id="caseCreationForm" asp-action="Create" method="post">
    <div class="form-group">
        <label asp-for="CaseTitle" class="control-label"></label>
        <input asp-for="CaseTitle" class="form-control" />
        <span asp-validation-for="CaseTitle" class="text-danger"></span>
    </div>
    <!-- Add all your other form fields here -->
    <button type="submit" class="btn btn-primary">Create Case</button>
</form>

Step 2: Add the AJAX + SweetAlert JavaScript

Put this script at the bottom of your Create view (or in a shared JS file) to handle the form submit asynchronously:

$(document).ready(function() {
    $('#caseCreationForm').submit(function(e) {
        // Stop the default form submission behavior
        e.preventDefault();

        const form = $(this);
        const formData = new FormData(form[0]); // Capture all form data including the anti-forgery token

        // Submit the form via AJAX
        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: formData,
            processData: false,
            contentType: false, // Required for FormData to work correctly
            success: function(response) {
                // Show success popup with the case number
                swal({
                    title: "Success!",
                    text: `Case Created! Your Case Number is ${response.caseNumber}`,
                    icon: "success",
                    button: "OK",
                }).then(() => {
                    // Redirect to your cases list page after the user clicks OK
                    window.location.href = '/Cases/Index';
                });
            },
            error: function(xhr) {
                // Show error popup if something goes wrong
                swal({
                    title: "Oops!",
                    text: "There was an error creating your case. Please check the form and try again.",
                    icon: "error",
                    button: "Try Again",
                });

                // Optional: Show validation errors from the server
                const errors = xhr.responseJSON;
                if (errors) {
                    $.each(errors, function(field, message) {
                        $(`[data-valmsg-for="${field}"]`).text(message)
                            .removeClass('field-validation-valid')
                            .addClass('field-validation-error');
                    });
                }
            }
        });
    });
});

Step 3: Modify Your Create Controller Action

Update your controller to return a JSON response instead of a view, so the AJAX call can receive the case number or validation errors:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CaseViewModel model)
{
    if (ModelState.IsValid)
    {
        // Create the case in your database
        var newCase = new Case
        {
            CaseTitle = model.CaseTitle,
            // Map all other properties from your model
        };
        _context.Cases.Add(newCase);
        await _context.SaveChangesAsync();

        // Return success JSON with the new case number
        return Json(new { success = true, caseNumber = newCase.CaseId });
    }

    // If validation fails, return errors as JSON
    var validationErrors = ModelState.ToDictionary(
        kvp => kvp.Key,
        kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).FirstOrDefault()
    );
    return BadRequest(validationErrors);
}

Quick Checks to Make Sure It Works

  • Ensure you've included jQuery and SweetAlert in your layout (or view):
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
  • Double-check that your anti-forgery token is included in the form (tag helpers add this automatically, but if you're writing HTML manually, add <input asp-for="__RequestVerificationToken" type="hidden" />).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:27:48