在 ASP.NET Core Razor 视图中 POST 错误时显示错误?

问题描述 投票:0回答:2

我正在尝试找出显示可在我的应用程序的所有页面中显示的通用错误消息的最佳方式。执行表单 POST 请求时应显示错误视图。

为了使错误视图在任何地方都可用,我将其放入 _Layout.cshtml 中,但我不太确定当我从表单提交 POST 请求时如何显示它。

注意:解决方案不应强制页面刷新(即应该是异步的)。

现在我正在使用

TempData
来存储和显示消息

这是我的_Layout.cshtml

<!DOCTYPE html>
...
<body>
@if (TempData["SystemError"] != null)
{
    <div>@TempData["SystemError"]</div>
}

@RenderSection("BodyFill", false)
@RenderBody()
...
@RenderSection("Scripts", required: false)
</body>
</html>

这是我的控制器操作:

[HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult ShareWorkbook(string emails, string title, string id, string queryBuilderId)
    {
        var emailStrArr = Regex.Split(emails, Constants.SplitPattern).ToList();

        var workbookShareModel = new WorkbookShareModel
        {
            Id = id,
            QueryBuilderId = queryBuilderId,
            Title = title,
            Emails = emailStrArr
        };

        // check to see if the 'WorkbookShareModel' is valid (takes into account its property DataAnnotation)
        if (TryValidateModel(workbookShareModel))
        {
            try
            {
                ShareWorkbook(workbookShareModel);
            }
            catch (Exception e)
            {
                //Todo -- Exception handling
                TempData["SystemError"] = Res.System_Error_Message;
            }
        }

        // return no content to avoid page refresh
        return NoContent();
    }

这就是表单(它位于加载到index.cshtml中的部分视图中)

@using DNAAnalysisCore.Resources
@model DNAAnalysisCore.Models.WorkbookShareModel
@* Partial view that contains the 'Share Workbook dialog' modal *@

<!-- Modal -->
<div onclick="activateShareButtons()" class="modal fade" id="shareFormModal" role="dialog">
    <div class="modal-dialog modal-md">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Share Workbook - @Model.Title</h4>

            </div>

            @using (Html.BeginForm("ShareWorkbook", "Home", FormMethod.Post, new { @id = "partialform" }))
            {
                <div class="modal-body">

                ...

                <div class="modal-footer">
                    <button onclick="hideDialog()" type="submit" class="btn btn-primary">Share</button>
                    <button onclick="activateShareButtons()" id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                </div>
            }

        </div>
    </div>
</div>
c# ajax asp.net-core razor razor-pages
2个回答
1
投票

我设法使用不显眼的 Ajax HTML 找到了一个解决方案(感谢 ASP.NET Core 返回“名称‘Ajax’在当前上下文中不存在’)。

我将原始

Html.BeginForm
(同步)代码转换为异步调用,在执行请求时刷新 div:

<form id = "partialform" asp-action="ShareWorkbook" asp-controller="Home" method="post" data-ajax="true" data-ajax-update="divEmp">
<div class="modal-body">
    ...
    <div class="modal-footer">
        <button onclick="hideDialog()" type="submit" class="btn btn-primary">Share</button>
        <button onclick="activateShareButtons()" id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
    </div>
</div>
</form>

_Layout.cshtml:

...
<body>
<div id="divEmp">
    @if (TempData["error"] != null)
    {
        <p>@TempData["error"]</p>
    }
</div>
@RenderSection("BodyFill", false)
@RenderBody()
...

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ShareWorkbook(string emails, string title, string id, string queryBuilderId)
{
    ...

    TempData["error"] = "TEST ERROR MESSAGE";
    // return no content to avoid page refresh
    return NoContent();
}

0
投票

在_Layout.cshtml中创建一个div

<div id="messageDiv"></div>

在 onclick 事件上使用 ValidateButton() 函数的部分视图中的按钮

<button onclick="ValidateButton()" id="btnCancelDialog" type="button" class="btn btn-default">Validate</button>

JQuery

function ValidateButton() {
   // If you have any parameter
    var obj ={
        parm: "1"
    };

    $.ajax({
        url: '/Home/ValidationProcess',
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        data: JSON.stringify(obj),
        cache: false,
        success: function (result) {
            $("#messageDiv").html(result);
        },
        error: function (xhr, status, error) {
            alert("Error");
        }
    });
}

控制器

public string ValidationProcess(string parm)
{
    // Do something

    return "Message";
}

不要忘记添加 JQuery 库

© www.soinside.com 2019 - 2024. All rights reserved.