PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] How to show alert message in ASP.NET Core Razor from PageModel

 August 04, 2022     .net, asp.net-core, exception, razor     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing