Search code examples
asp.net-coreexceptionrazor

How to show an alert message in ASP.NET Core Razor syntax from PageModel


I want to show an alert message to client when an exception is raised in the PageModel. What's the way to achieve this task in ASP.NET Core Razor syntax?


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/[email protected]/dist/sweetalert2.all.min.js"></script>
    
    <script>
       $(document).ready(function () {
          let msg = $('#StatusMessage').val();
          if(msg.length > 0) {
              swal.fire(msg);
          }
       }
    </script>