Home > Enterprise >  How to trigger html code (modal popup) from OnPost handler in razor pages?
How to trigger html code (modal popup) from OnPost handler in razor pages?

Time:10-26

Most of the time we are hitting submit button and triggering OnPost handler to do some stuff. I need to do something opposite. I would like to trigger the modal(html code) after OnPost is executed only if ModelState.IsValid . How to do achieve that?

CodePudding user response:

You can try to use ajax to pass form data to OnPost handler,and then check ModelState and pass data to the view,if ModelState.IsValid,open the modal,here is a demo:

cshtml:

<form method="post" id="myForm">
    <input name="name" value="test" />
    <input type="button" value="submit" onclick="submitForm()"/>
</form>
<div id="myModal"  tabindex="-1" role="dialog">
  <div  role="document">
    <div >
      <div >
        <h5 >Modal title</h5>
        <button type="button"  data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div >
        <p>Modal body text goes here.</p>
      </div>
      <div >
        <button type="button" >Save changes</button>
        <button type="button"  data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
@section Scripts{
    <script>
        function submitForm() {
            $.ajax({
                type: "POST",
                url: "?handler=Test",
                data: $("#myForm").serialize(),
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function(data) {
                    if (data == "open") {
                        $("#myModal").modal("show");
                    }
                }
            });

        }
    </script>

}

cshtml.cs:

 public JsonResult OnPostTest(User user)
        {
            if (ModelState.IsValid)
            {
                return new JsonResult("open");
            }
            return new JsonResult("");
        }

User:

public class User {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }

    }

result: enter image description here

  • Related