Search code examples
asp.net-corerazor-pages

Razor Page Call Modal From Code Behind on post async


I read a barcode and save the user in the database by posting back once I read the code, while in the OnPostAsync I validate on the user and I want to show a popup window if the user renewal date is expired? so how can I do this?


Solution

  • You can use ajax to call OnPostAsync and then show a popup in ajax success.Here is a demo:

    cshtml(you can put the data you want to pass into data of ajax):

    @Html.AntiForgeryToken()
    <button onclick="postdata()">submit</button>
    @section Scripts
    {
        <script>
            function postdata() {
                $.ajax({
                    type: "POST",
                    url: '',
                    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                    data: { id: 1 }
                }).done(function (result) {
                    if (result.message != "") {
                        alert("message:"+result.message);
                        }
                        
                    });
                    
            }
        </script>
    
    }
    

    cshtml.cs:

    public async Task<IActionResult> OnPostAsync(int id)
            {
                //you can check if the user renewal date is expired here 
                if (id==1)
                {
                    return new JsonResult(new{ message = "user renewal date is expired" });
                }
                else {
                    return new JsonResult(new { message = "" });
                }
            }
    

    result: enter image description here