Search code examples
asp.net-corerazorpopupalert

Show Post submit popup message in ASP.Net Core Razor page without controller


I have an ASP.Net Core Razor web application without controllers. I have a form in my cshtml page and on Post/Submit I am calling an external API, which returns a success message or an error message. I want to show this message in my page as a popup. I tried multiple things but failed. Here is my code.

In my "Index.cshtml"

<div class="col-lg-4 col-md-6 footer-newsletter">
     <h4>Our Newsletter</h4>
     <p>Subscribe to our news letter</p>
     <form action="" method="post">
           <input type="email" asp-for="SubscriptionEmail" placeholder="Email Address"/>
           <input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
     </form>
</div>

In my Index.cshtml.cs

[BindProperty]
public string SubscriptionEmail { get; set; }

public string ActionResultMessageText { get; set; }
public string ActionResultErrorMessageText { get; set; }

public async void OnPostNewsSubscription()
{
    try
    {
        this.ActionResultMessageText = string.Empty;
        this.ActionResultErrorMessageText = string.Empty;
        using (HttpClient _httpClient = _httpClientFactory.CreateClient("PortalBasicHttpClient"))
        {
            if (!string.IsNullOrEmpty(SubscriptionEmail))
            {
                HttpRequestMessage _Request = new(HttpMethod.Post, _httpClient.BaseAddress + "Api/SaveSubscriptionEmail/" + SubscriptionEmail);
                HttpResponseMessage _Response = await _httpClient.SendAsync(_Request);
                if (_Response.IsSuccessStatusCode)
                {
                    this.ActionResultMessageText = _Response.Content.ReadAsStringAsync().Result.ToString();
                }
                else
                {
                    this.ActionResultMessageText = _Response.Content.ReadAsStringAsync().Result.ToString();
                }           
            }
       }
   }
   catch (Exception ex)
   {
       _logger.LogError(ex, ex.Message);
       this.ActionResultMessageText = string.Empty;
       this.ActionResultErrorMessageText = ex.Message;
                
    }
            
}

My code behind is working fine, but not sure how to grace fully show this in the razor page using bootstrap. looking forward for some guidance.

I tried using modal popup, but the text was not updated in the label I used in the modal popup and the pop-up disappeared with in few seconds, even though there was a "ok" button.

I also tried to use the java script method as mentioned in the following link https://www.aspsnippets.com/Articles/ASPNet-Core-Razor-Pages-Display-JavaScript-Alert-Message-Box.aspx

I will be great help if someone can help with a sample code.


Solution

  • Please debug your code and be sure the two properties actually contain the value you want.

    The following working demo I just hard coded the two properties value for easy testing in the backend:

    Index.cshtml

    @page
    @model IndexModel
    <div class="col-lg-4 col-md-6 footer-newsletter">
        <h4>Our Newsletter</h4>
        <p>Subscribe to our news letter</p>
        <form action="" method="post">
            <input type="email" asp-for="SubscriptionEmail" placeholder="Email Address" />
            <input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
        </form>
    </div>
    @if (Model.ActionResultMessageText == string.Empty)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@Model.ActionResultErrorMessageText");
            };
        </script>
    }
    

    Index.cshtml.cs

    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
    
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }
        [BindProperty]
        public string SubscriptionEmail { get; set; }
    
        public string ActionResultMessageText { get; set; }
        public string ActionResultErrorMessageText { get; set; }
        public void OnGet()
        {
            
        }
        public async void OnPostNewsSubscription()
        {
            this.ActionResultMessageText = string.Empty;
            this.ActionResultErrorMessageText = "error";
    
        }
    }
    

    Result:

    enter image description here


    If you want to use Bootstrap modal popup, change your page like below:

    @page
    @model IndexModel
    <div class="col-lg-4 col-md-6 footer-newsletter">
        <h4>Our Newsletter</h4>
        <p>Subscribe to our news letter</p>
        <form action="" method="post">
            <input type="email" asp-for="SubscriptionEmail" placeholder="Email Address" />
            <input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
        </form>
    </div>
    
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
                @Model.ActionResultErrorMessageText       
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>
    @if (Model.ActionResultMessageText == string.Empty)
    {
        <script type="text/javascript">
            window.onload = function () {
                $("#exampleModal").modal("show")
            };
        </script>
    }
    

    Result: enter image description here