2

I want to know how can I retrieve success and model error and display it in my modal if the post is called via ajax? If success modal must close and if error, a modal should display the custom error and not close modal. So far here is my code:

this is called when the user clicks the save button function:

    if (result.value) {
    
                    var actionUrl = form.attr('action');
                    var sendData = form.serialize();
    
                    $.post(actionUrl, sendData).done(function (data) {
    
                        //Error here
                        //what code to retrieve error here?
                        //end error
    
                        //Success here
                        swalWithBootstrapButtons.fire(
                            'Saved!',
                            'Your data has been saved.',
                            'success'
                        )
    
                        PlaceHolderElement.find('.modal').modal('hide');
                        //end success
                    });


                } else if (
                    /* Read more about handling dismissals below */
                    result.dismiss === Swal.DismissReason.cancel
                ) {
                }
}

And here is my controller code:

     [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Create(string company, MemberVM member)
            {
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser { UserName = member.Email, Email = member.Email, SiteName = company, Status=true, DateCreated = DateTime.Now, EmailConfirmed = true };
                    var result = await _userManager.CreateAsync(user, "Password123!");
                    if (result.Succeeded)
                    {
    
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
    
                        return PartialView();
                    }
    }
return PartialView();
    }

And I know my validationscripts are working fine, sample screenshot

enter image description here

Pritom Sarkar
  • 2,154
  • 3
  • 11
  • 26
Asdf1234567
  • 476
  • 1
  • 10
  • 25
  • https://stackoverflow.com/questions/18893814/prevent-bootstrap-modal-window-from-closing-on-form-submission you can prevent your model from closing, later instead of returning PartialView you can return json, if you want to check if user made an ajax request you can check from Request.IsAjaxRequest I think. – abdul qayyum Dec 12 '21 at 11:18

1 Answers1

0

You can try to return error messages to view rather than returning a PartialView.And put the error messages into somewhere you want.

[HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<Dictionary<string, string>> Create(string company, MemberVM member)
            {
                Dictionary<string, string> d = new Dictionary<string, string>();
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser { UserName = member.Email, Email = member.Email, SiteName = company, Status=true, DateCreated = DateTime.Now, EmailConfirmed = true };
                    var result = await _userManager.CreateAsync(user, "Password123!");
                    if (result.Succeeded)
                    {
    
                    }
                    else
                    {   
                        foreach (var error in result.Errors)
                        {
                            d.Add("propertyName", error.Description);
                        }
    
                        return d;
                    }
    }
return d;
    }

View Modal:

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form method="post">
                    <div class="form-group">
                        <label asp-for="FirstName" class="control-label"></label>
                        <input asp-for="FirstName" class="form-control" />
                        <span asp-validation-for="FirstName" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="LastName" class="control-label"></label>
                        <input asp-for="LastName" class="form-control" />
                        <span asp-validation-for="LastName" class="text-danger"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="CallJs()">Save changes</button>
            </div>
        </div>
    </div>
</div>

js:

$.post(actionUrl, sendData).done(function (data) {
    
                        //Error here
                        //what code to retrieve error here?
                        //end error
                        if (Object.keys(data).length != 0) {
                        //if the dictionary is not empty,add error to corresponding span of input
                        for (const [key, value] of Object.entries(data)) {
                            $("span[data-valmsg-for=" + key + "]").html(value);
                        }
                        } else {
                            //if the dictionary is empty,close the modal
                            PlaceHolderElement.find('.modal').modal('hide');
                        }
    
                        //Success here
                        swalWithBootstrapButtons.fire(
                            'Saved!',
                            'Your data has been saved.',
                            'success'
                        )
    
                        
                        //end success
                    });
Yiyi You
  • 16,875
  • 1
  • 10
  • 22