I am trying to figure out what is the best way to show a generic error message that can be shown in all of the pages in my app. The error view should be shown when a form POST request is executed.
To make the error view available everywhere I've put it in the _Layout.cshtml but I am not quite sure how show it when I submit a POST request from my form.
Note: the solution should not force the page to refresh (i.e. should be asynchronous).
Right now I am using TempData
to store and show the message
This is my _Layout.cshtml
<!DOCTYPE html>
...
<body>
@if (TempData["SystemError"] != null)
{
<div>@TempData["SystemError"]</div>
}
@RenderSection("BodyFill", false)
@RenderBody()
...
@RenderSection("Scripts", required: false)
</body>
</html>
This is my controller action:
[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();
}
That is the form (it's in a partial view that is loaded into the 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>