首页 > 解决方案 > 如何打开引导模式窗口弹出窗口而不是在新窗口中打开它?

问题描述

我试图在用户提交表单时弹出一个模式窗口,向用户列出任何验证错误。使用我当前的代码,该窗口将作为一个全新的视图而不是模式窗口打开。我怎样才能让这个窗口与表单的视图重叠而不是打开一个全新的视图?

控制器

[HttpPost]
public IActionResult Daily(Daily dailyReport)
{
    var dr = new ReportDaily();
    var rc = new ReportDailyCriteria();
    dr.Preview(rc, IntPtr.Zero, out Notification notification);
    if (notification.HasErrors) {
        var error = new Errors();
        string errorString = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine);
        error.ErrorList = errorString;
        return PartialView("_ErrorsModal", error);
    }
    return View(dailyReport);
}

局部视图

@model Test.Areas.Reports.Models.Errors
<!-- Modal -->
<div id="errorsModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title float-left">Error List</h4>
                <button type="button" class="close" data-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <label>Errors: @Model.ErrorList</label>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
            </div>
        </div>

    </div>
</div>

标签: javascriptc#ajaxasp.net-mvcasp.net-core

解决方案


  1. 据我了解,您将表单作为完整回发发布到控制器操作。相反,您需要将其作为ajax帖子发送,这将使您能够灵活地处理响应。
  2. 我建议在初始页面加载时呈现您的模式,然后仅JSON在从控制器接收结果时使用。它将消除复杂的响应解析逻辑(确定它是部分视图还是其他适当的进一步操作)。

所以在主视图上渲染你的部分视图(Errors: @Model.ErrorList从部分视图中删除并将标签留空,因为你不再需要它了):

@Html.Partial("_ErrorsModal")

您将返回的控制器操作Json

    [HttpPost]  
    public IActionResult Daily(Daily dailyReport)  
    {  
        var dr = new ReportDaily();
        var rc = new ReportDailyCriteria();
        dr.Preview(rc, IntPtr.Zero, out Notification notification);
        if (notification.HasErrors) 
        {
            return Json(new
            {
                success = false,
                message = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)
            });
        }

        return Json(new { success = true });
    }

ajax当您发布表格时您的电话 :

    $.ajax({
        type: 'POST',
        data: JSON.stringify($('#your_form_id').serializeArray().reduce(function(m,o){ m[o.name] = o.value; return m;}, {})),
        url: 'http://your_website/your_controller/Daily',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if(data.success){
                //your actions when validation successful...
            } else {
                $('#errorsModal .modal-body label').html(data.message);
                $('#errorsModal').modal('toggle');
            }
        }
    });

推荐阅读