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

ASP.NET Core 7 MVC模态框中模型验证错误显示问题

模态框内处理筛选表单的模型验证错误

我的Index视图以List<Rental>为模型,用来展示所有租赁记录。期望流程是:

  • 用户点击「Filter!」按钮弹出筛选模态框
  • 选择筛选条件后点击「Submit」
  • 若模型验证失败,模态框保持打开并显示错误信息
  • 若验证通过,加载筛选后的Index视图展示结果

当前实现遇到的问题:模型验证失败时,返回的_FilterPartial局部视图会直接独立显示在新页面,而不是留在模态框内展示错误。


解决方案

1. 修改前端表单提交逻辑(AJAX提交)

修改Index.cshtml中的脚本,为筛选表单添加AJAX提交处理,拦截默认提交行为:

<script>
    $('#filterButton').click(function () {
        $('#filterModal .modal-dialog').load('/Home/GetFilterPartial', function() {
            // 加载完局部视图后绑定表单提交事件
            $('#filterForm').on('submit', function(e) {
                e.preventDefault(); // 阻止默认表单提交

                var formData = $(this).serialize();
                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.isRedirect) {
                            // 验证通过,刷新页面到筛选结果
                            window.location.href = response.redirectUrl;
                        } else {
                            // 验证失败,更新模态框内容为带错误的局部视图
                            $('#filterModal .modal-dialog').html(response);
                        }
                    }
                });
            });
        });
        $('#filterModal').modal('show');
    });
</script>

2. 调整控制器逻辑

修改HomeController.cs中的POST方法,根据模型状态返回不同的响应:

[HttpPost]
[Route("/Results")]
public async Task<IActionResult> IndexAsync(FilterViewModel vm)
{
    if (ModelState.IsValid)
    {
        // 执行筛选逻辑
        var rentals = // 你的筛选查询逻辑
        return Json(new { 
            isRedirect = true, 
            redirectUrl = Url.Action("Index") // 跳转至筛选后的Index页面
        });
    }

    // 验证失败,返回带错误的局部视图HTML内容
    var partialView = PartialView("_FilterPartial", vm);
    using (var writer = new StringWriter())
    {
        var viewContext = new ViewContext(
            ControllerContext,
            partialView.View,
            partialView.ViewData,
            partialView.TempData,
            writer,
            new HtmlHelperOptions()
        );
        await partialView.View.RenderAsync(viewContext);
        return Content(writer.ToString(), "text/html");
    }
}

3. 确保局部视图的验证提示正常显示

确认_FilterPartial.cshtml中的验证摘要和字段验证提示正确配置,示例如下:

@model FilterViewModel

<div class="modal-content">
    <form asp-controller="Home" asp-action="Index" id="filterForm" method="post">
        <div class="modal-header">
            <h5 class="modal-title">Wanna filter?</h5>
            <button class="btn-close" type="button" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body d-grid gap-3">
            <div class="row">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            </div>
            
            <!-- 替换为你的FilterViewModel字段示例 -->
            <div class="mb-3">
                <label asp-for="StartDate" class="form-label"></label>
                <input asp-for="StartDate" class="form-control" />
                <span asp-validation-for="StartDate" class="text-danger"></span>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Close</button>
            <button class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>

原理说明

  • 通过AJAX提交表单,避免页面直接跳转,能够精准控制响应处理逻辑
  • 控制器验证通过时返回JSON标记,指示前端刷新页面展示筛选结果
  • 验证失败时返回局部视图的HTML内容,前端将其替换模态框内的内容,保持模态框打开状态并显示错误信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:15:04