Home > Net >  Display Confirmation bootstrap Modal when ModelState is valid using an ajax POST from Razor View
Display Confirmation bootstrap Modal when ModelState is valid using an ajax POST from Razor View

Time:04-23

I have a scenario where I need to display a confirmation modal after the primary model has been validated on the server - using data annotations , but I want to actual commit to the DB to happen in the confirmation modal and not the main razor view:

Every thing works as expected except that I cannot wrap my head around how I display the confirmation partial view in a modal. I get redirected to the partial view alright but I just need it in a modal:

See pseudocode below:

C# - actions

[HttpGet]
public IActionResult ConfirmUser()
{
    //Get TempData model here:
    return PartialView(model);
}


[HttpPost]
public IActionResult ConfirmUser(ConfirmUser usermodel)
{
   //UserService.ConfirmUser(usermodel)
}

[HttpPost]
public IActionResult AddNewUser(UserModel)
{
    if (ModelState.IsValid)
    {
        //Some TempData logic here:

        return RedirectToAction("ConfirmUser");

    }
    return View(UserModel);
}

Js -in Razor View

      $("#add-new-User-form").submit(function (e) {

       e.preventDefault();
        var $form = $(this);
        $.post($form.attr("action"),
 $form.serialize())
.done(function(dt, status, req)
        {

           if ($form.valid()) {

                $('#add-job-container').html(dt); //container
                $('#add-job-modal').modal('show'); //modal

            } else
            {
                //???

            }
         

        })

     });

the $form.valid() works but is only client side. I have also tried using ViewData.ModelState.IsValid on the view to no avail. I assume I'd need to be returning Json objects from the actions and render the form on that basis ?

CodePudding user response:

1.If you want to display confirmation modal, you cannot use RedirectToAction in the backend, because ajax cannot handle redirect operation from backend.

2.You cannot access the ModelState in client side, it only works in server side.

I saw you return current view with model(return View(UserModel);) when ModelState is invalid. Without ajax this code is used to display the form you filled and the error message. Actually, by using ajax in your scenario it will always maintain the filled form and display error message.

If you just want to display the view with model data and error message, I suggest you return BadRequest in backend. Then it will get into the ajax.error function and no need judge $form.valid().

A whole working demo you could follow:

Model:

public class UserModel
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Email { get; set; }
}

View:

AddNewUser.cshtml

@model UserModel
<form asp-action="AddNewUser" id="add-new-User-form">
    <div>
        <label>Name</label>
        <input asp-for="Name" />
        <span asp-validation-for="Name" ></span>
    </div>
    <div>
         <label>Email</label>
         <input asp-for="Email" />
        <span asp-validation-for="Email" ></span>
    </div>
    <input type="submit"  value="ADD" />
</form>


<div  id="add-job-modal" tabindex="-1"  aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div  role="document">
    <div >
      <div >
        <h5 >Modal title</h5>
        @*<button type="button"  data-dismiss="modal" aria-label="Close">  bootstrap version 4.x*@
        <button type="button"  data-bs-dismiss="modal"="modal" aria-label="Close"> @*bootstrap version 5.x*@

          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div  id="add-job-container">
        
      </div>
      <div >
        <button type="button" >Save changes</button>
        <button type="button"  data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
@section Scripts
{ 
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
    <script>
        $("#add-new-User-form").submit(function (e) {
            e.preventDefault();
            var $form = $(this);
            $.post($form.attr("action"), $form.serialize())
                .done(function(dt, status, req)
                {
                    $('#add-job-container').html(dt); //container
                    $('#add-job-modal').modal('show'); //modal       
                })
                .fail(function(res){
                    //ModelState is invalid 
                    //do your stuff..
                    alert(res.statusText);
                })
         });
     </script>
}

ConfirmUser.cshtml

@model UserModel
<h1>Confirm User</h1>
@Model.Name
@Model.Email

Controller:

public IActionResult AddNewUser()
{
    return View();
}
[HttpPost]
public IActionResult AddNewUser(UserModel model)
{
    if (ModelState.IsValid)
    {
        //Some TempData logic here:
        return PartialView("ConfirmUser",model);
    }
    return BadRequest();
}

Result:

enter image description here

  • Related