无控制器的ASP.NET Core Razor页面实现提交后弹窗提示
ASP.NET Core Razor页面Bootstrap弹窗展示API返回结果示例
方案1:表单提交后重定向展示Toast(传统提交方式)
后台PageModel代码(Index.cshtml.cs)
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.Net.Http.Json; namespace YourProjectNamespace.Pages { public class IndexModel : PageModel { private readonly HttpClient _httpClient; public IndexModel(HttpClient httpClient) { _httpClient = httpClient; } // 绑定表单字段,替换为你的实际字段 [BindProperty] public string FormContent { get; set; } public async Task<IActionResult> OnPostAsync() { try { // 调用外部API,替换为你的API地址和请求参数 var apiResponse = await _httpClient.PostAsJsonAsync( "https://your-external-api-url.com/api/action", new { Content = FormContent }); apiResponse.EnsureSuccessStatusCode(); var result = await apiResponse.Content.ReadFromJsonAsync<ApiResult>(); // 存储成功消息和状态到TempData(仅保留一次请求) TempData["AlertMessage"] = result.SuccessInfo; TempData["IsSuccess"] = true; } catch (Exception ex) { // 捕获异常,存储错误消息 TempData["AlertMessage"] = $"请求失败:{ex.Message}"; TempData["IsSuccess"] = false; } // 重定向回当前页面,避免表单重复提交 return RedirectToPage(); } // 根据外部API返回结构定义模型,自行调整字段 private class ApiResult { public string SuccessInfo { get; set; } } } }
前端Razor页面代码(Index.cshtml)
@page @model IndexModel @{ ViewData["Title"] = "表单提交页面"; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <div class="container mt-4"> <form method="post"> <!-- 表单内容 --> <div class="mb-3"> <label class="form-label">输入内容</label> <input type="text" class="form-control" asp-for="FormContent" required> </div> <button type="submit" class="btn btn-primary">提交</button> </form> </div> <!-- Bootstrap Toast 提示组件 --> <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11"> <div id="alertToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <strong class="me-auto" id="toastTitle">@(TempData["IsSuccess"] != null && (bool)TempData["IsSuccess"] ? "成功" : "错误")</strong> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body"> @TempData["AlertMessage"] </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script> $(function() { // 页面加载时检查是否有消息,有则弹出Toast const message = '@TempData["AlertMessage"]'; if (message && message.trim()) { // 根据状态设置Toast样式 const toastEl = $('#alertToast'); toastEl.addClass((bool)@TempData["IsSuccess"] ? 'text-bg-success' : 'text-bg-danger'); // 初始化并展示Toast const toast = new bootstrap.Toast(toastEl[0]); toast.show(); } }); </script>
方案2:Ajax无刷新提交+动态弹窗(流畅交互)
后台PageModel代码调整
将OnPostAsync方法改为返回JSON:
public async Task<IActionResult> OnPostAsync() { try { var apiResponse = await _httpClient.PostAsJsonAsync( "https://your-external-api-url.com/api/action", new { Content = FormContent }); apiResponse.EnsureSuccessStatusCode(); var result = await apiResponse.Content.ReadFromJsonAsync<ApiResult>(); return new JsonResult(new { IsSuccess = true, Message = result.SuccessInfo }); } catch (Exception ex) { return new JsonResult(new { IsSuccess = false, Message = $"请求失败:{ex.Message}" }); } }
前端代码调整
@page @model IndexModel @{ ViewData["Title"] = "Ajax提交页面"; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <div class="container mt-4"> <form id="submitForm"> <div class="mb-3"> <label class="form-label">输入内容</label> <input type="text" class="form-control" id="formContent" name="FormContent" required> </div> <button type="submit" class="btn btn-primary">提交</button> </form> </div> <!-- Toast 组件 --> <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11"> <div id="alertToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <strong class="me-auto" id="toastTitle"></strong> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body" id="toastMessage"></div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script> $(function() { $('#submitForm').submit(function(e) { e.preventDefault(); // 阻止默认表单提交 // 收集表单数据 const formData = { FormContent: $('#formContent').val() }; // 发送Ajax请求 $.ajax({ type: 'POST', url: '/Index?handler=OnPost', beforeSend: function(xhr) { // 传递防跨站伪造令牌 xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val()); }, data: formData, success: function(res) { showToast(res.IsSuccess, res.Message); // 清空表单 $('#formContent').val(''); }, error: function(xhr) { showToast(false, "请求出错,请稍后重试"); } }); }); // 统一弹窗方法 function showToast(isSuccess, message) { const toastEl = $('#alertToast'); // 清除旧样式,添加新样式 toastEl.removeClass('text-bg-success text-bg-danger'); toastEl.addClass(isSuccess ? 'text-bg-success' : 'text-bg-danger'); // 更新文本内容 $('#toastTitle').text(isSuccess ? '成功' : '错误'); $('#toastMessage').text(message); // 展示Toast const toast = new bootstrap.Toast(toastEl[0]); toast.show(); } }); </script>
方案3:使用Bootstrap模态框展示(手动关闭)
如果偏好模态框,替换前端的Toast为以下代码,并保留方案1的后台逻辑:
<!-- Bootstrap 模态框 --> <div class="modal fade" id="messageModal" tabindex="-1" aria-labelledby="modalTitle" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header @(TempData["IsSuccess"] != null && (bool)TempData["IsSuccess"] ? "bg-success text-white" : "bg-danger text-white")"> <h5 class="modal-title" id="modalTitle">@(TempData["IsSuccess"] != null && (bool)TempData["IsSuccess"] ? "操作成功" : "操作失败")</h5> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> @TempData["AlertMessage"] </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> </div> </div> </div> </div> <!-- 替换原Toast的JS代码 --> <script> $(function() { const message = '@TempData["AlertMessage"]'; if (message && message.trim()) { const modal = new bootstrap.Modal(document.getElementById('messageModal')); modal.show(); } }); </script>
关键注意事项
- 确保Bootstrap与jQuery版本兼容(Bootstrap 5需要jQuery 3.6及以上)
- TempData仅保留一次请求数据,适合重定向场景;Ajax场景直接通过JSON返回结果更高效
- 防跨站请求伪造(CSRF):Ajax提交时必须传递
__RequestVerificationToken,Razor页面会自动生成该令牌
内容的提问来源于stack exchange,提问作者Mrinmoy Das
相关产品推荐
相关产品推荐

