我尝试使用Ajax执行POST表单请求时出现错误时显示错误消息(我不希望页面刷新)。但是,下面的代码不会更改-尽管TempData["Error]
变量不为null(在控制器的操作中设置),它仍然显示“ NO ERRORS”。我做错了什么?
那是我的 _Layout.cshtml (我希望能够从每个页面显示此错误消息)
<!DOCTYPE html>
<html>
@*@RenderBody()*@
<head>
</head>
<body>
<div id="divEmp">
@if (TempData["Error"] != null)
{
<div class="alert alert-danger" role="alert">"Error here"</div>
}
else
{
<div class="alert alert-success" role="alert">NO ERRORS</div>
}
</div>
@RenderSection("BodyFill", false)
@RenderBody()
@RenderSection("Scripts", required: false)
</body>
</html>
那是我的 Controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ShareWorkbook(string emails, string title, string id, string queryBuilderId)
{
TempData["Error"] = Res.System_Error_Message;
return NoContent();
}
这是我的表单(位于局部视图中,并且在运行时注入到主页中)
@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>
<form id="partialform" asp-action="ShareWorkbook" asp-controller="Home" method="post" data-ajax="true" data-ajax-update="divEmp">
<div class="modal-body">
...
</div>
<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>
</form>
</div>
</div>
</div>
答案 0 :(得分:1)
您可以在Ajax的回调函数中使用javascript直接修改HTML标记。我假设在您的_Layout.cshtml中:
<div id="divEmp">
<div id="showError" style="display:none;" class="alert alert-danger" role="alert">"Error here"</div>
<div id="noError" style="display:none;" class="alert alert-success" role="alert">NO ERRORS</div>
</div>
在您的页面中,您将使用ajax调用服务器端功能,并根据响应可以直接显示/修改以上区域:
$(function () {
$.ajax({
type: "POST",
url: '/Home/GetJobData',
contentType: 'application/json; charset=utf-8',
success: function (response) {
if (response.success) {
$("#showError").hide();
$("#noError").show();
}
else {
$("#showError").show();
$("#noError").hide();
$("#showError").text(response.responseText);
}
},
error: function (response) {
alert("error!");
}
});
})
服务器端功能:
public IActionResult GetJobData()
{
var isFileSupported = true;
if (!isFileSupported)
{
// Send "false"
return Json(new { success = false, responseText = "Your operation fail !" });
}
else
{
// Send "Success"
return Json(new { success = true, responseText = "Your operation Success !" });
}
}