Issue
I'm newbie in ASP.NET Core. I want to show an alert message to client when an exception is raised in the PageModel. What's the best way to achieve this task?
Solution
Suppose you have a PageModel class where you have declared a variable like this one
public class CustomerEditModel() : PageModel
{
[TempData]
public string StatusMessage {get;set;}
.....
}
Inside this class the Post method finds itself in an exception condition of some type
public async Task<IActionResult> OnPostAsync()
{
....
catch(Exception ex)
{
_logger.LogError(ex, "Exception in post");
StatusMessage = "An error occurred while saving customer data!";
return Page();
}
}
Now in the matching RazorPage you have an hidden field that is linked to the StatusMessage property above
<div class="d-none">
<input asp-for="StatusMessage"/>
</div>
finally you add a javascript block that uses JQuery and SweetAlert to display your message box
@section Scripts {
<script> src="https://cdn.jsdelivr.net/npm/sweetalert2@11.1.7/dist/sweetalert2.all.min.js"></script>
<script>
$(document).ready(function () {
let msg = $('#StatusMessage').val();
if(msg.length > 0) {
swal.fire(msg);
}
}
</script>
Answered By - Steve Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.