简体   繁体   English

如何将部分视图错误模式从 MVC 控制器渲染到另一个视图中?

[英]How can I render a partial view error modal into another view from a MVC controller?

I would like to have this error modal window appear if there are issues or errors that need to be displayed to the user after calling the SaveDailyCriteria action.如果在调用 SaveDailyCriteria 操作后需要向用户显示问题或错误,我希望出现此错误模式窗口。 I need the partial view to be rendered within the view where the SaveDailyCriteria action call is made.我需要在调用 SaveDailyCriteria 的视图中呈现局部视图。 With the code that I currently have below, the return PartialView("_ErrorsModal", notification) gets called but is never displayed on my main view.使用我目前在下面的代码, return PartialView("_ErrorsModal", notification)被调用但从未显示在我的主视图上。

Controller控制器

[HttpPost]
public ActionResult SaveDailyCriteria(Daily report, string EnteredCriteriaName)
{
    var criteria = report.ConvertToCriteria(report);
    criteria.CriteriaName = EnteredCriteriaName;
    var dr = new ReportDaily();
    var nameExists = dr.DoesCriteriaNameAlreadyExist(criteria);
    if (dr.SaveReportCriteria(criteria, nameExists, out Notification notification) == false)
    {
        return PartialView("_ErrorsModal", notification);
    }
    else {
        return View(report);
    }
}

Main View主视图

@model Company.Areas.Reports.Models.Daily
@using Company.TaxCollection.Reports;
@{
    ViewData["Title"] = "Daily Report";
}

<h1>@ViewData["Title"]</h1>
<br />

@using (Html.BeginForm("DailySubmit", "Reports", FormMethod.Post, new { id = "reportForm", @class = "report-form col-9" }))
{
...
...
<div id="saveModal" 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">Save Criteria</h4>
                <button type="button" class="close" data-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <label>Enter the name to save as:</label><input type="text" id="savedReportName" name="EnteredCriteriaName" class="form-control" />
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="saveSubmit" data-dismiss="modal">Save</button>
            </div>
        </div>

    </div>
</div>
}
<script>
$(document).ready(function () {
    var dataType = 'application/x-www-form-urlencoded; charset=utf-8';
    $(function () {
        $('#saveSubmit').on('click', function (evt) {
            var data = $('form').serialize();
            //Ajax form post
            $.ajax({
                type: 'POST',
                data: data,
                contentType: dataType,
                url: '@Url.Action("SaveDailyCriteria", "Reports")',
                success: function (data) {
                    console.log(data);
                    if (data.success) {
                        //window.location.href = data;
                    } else {
                        //window.location.href = data;
                    }
                }
            });
        });
    });
});
</script>

_ErrorsModal Partial View _ErrorsModal 局部视图

@model Company.NotificationPattern.Notification
<!-- 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">Warning</h4>
                <button type="button" class="close" data-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                @if (Model.HasErrors || Model.HasWarnings) {
                    <p>@Model.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)</p>
                }
            </div>
            <div class="modal-footer">
                <button type="button" id="modalConfirm" class="btn btn-primary" data-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
</div>

You can achieve this various ways, one option:您可以通过多种方式实现这一点,一种选择:

  • In your controller post method, return a json when it passes and the partial when it fails.在您的控制器 post 方法中,通过时返回 json,失败时返回部分。
  • Within your jquery $.ajax post check for json and proceed otherwise render the result to your modal在您的 jquery $.ajax post 检查 json 并继续将结果呈现给您的模态

In your case, the json returned on pass would indicate the url of the view to redirect to (not the view itself otherwise there's no way to know if it's a new view or the partial error).在您的情况下,传递时返回的 json 将指示要重定向到的视图的 url(不是视图本身,否则无法知道它是新视图还是部分错误)。 eg例如

if (save() == false)
{
    return PartialView("_ErrorsModal", notification);
}
else {
    return Json({ 
        success = true, 
        url = this.Url.Action("SaveDailyCriteria", new { reportId = report.ReportId }
    });
}

and your javascript to:和你的 javascript 到:

$.ajax({
    type: 'POST',
    ...
    success: function (data) {
        if (data.success) 
            window.location.href = data.url;
        else
            $("#modalId").html(data);
    }
});

the alternative is to always return json but render the _ErrorsModal (on error) or View (on success) within the controller to a string and add that string as a json property.另一种方法是始终返回 json,但将控制器中的 _ErrorsModal(出错时)或 View(成功时)呈现为一个字符串,并将该字符串添加为 json 属性。 IMO better to let the MVC pipeline handle rendering to HTML so recommend the above approach. IMO 最好让 MVC 管道处理 HTML 渲染,因此推荐上述方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM