Home > Software engineering >  How to show alert message in ASP.NET Core Razor from PageModel
How to show alert message in ASP.NET Core Razor from PageModel

Time:01-28

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?

CodePudding user response:

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 >
   <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>

Do not forget to always set the StatusMessage variable to empty in the Get method even if the TempData attribute has been applied.

  •  Tags:  
  • Related