Search code examples
ajaxasp.net-corebootstrap-4bootstrap-modal

Close Bootstrap Modal and show another after ajax call


in my project I'm Working with Asp core 3.1, I'm saving data with ajax using bootstrap modal and it saves but modal didn't hide in success and I want to show another modal with data feedback it didn't show either it shows dialog with html markup like in picture enter image description here so here is my ajax Code

 $('#btnSave').click(function (event) {
    event.preventDefault();
    Add();
});
function Add() {
    var res = Validate();  
    if (res == false) {
        return false;
    }  
   
    var CategoryObj = {
        CategoryName: $("#inputCategory").val()
    };
    $.ajax({
        url: "/Writer/SaveCategory",
        data: JSON.stringify(CategoryObj),
        type: "POST",
        contentType: "application/json;charset=utf-8", 
        dataType: "json",
        success: function (result) {
            
            $('#NewCategory').modal('hide');

             $("#content").html(result);
            $("#ResultCategory").modal("show");
            $("#ResultCategory").appendTo("body");;
        },  
        error: function (errormessage) {
            alert(errormessage.responseText);
        }  
    });
}

and in my controller code

    [HttpPost]
    public async Task<IActionResult> SaveCategory([FromBody]CategoryModelDto categoryModel)
    {
        CategoryModelDto categoryModelDto = new CategoryModelDto();
        if (ModelState.IsValid==true)
        {
            categoryModelDto= await _categoryService.CreateNewCategory(categoryModel);
        }
        
        return PartialView("_CategoryResult", categoryModelDto);
    }

and my view

<button type="button" id="addCategory" style="margin-left:15px;" class="btn btn-primary">
New Category
<div class="modal fade" id="NewCategory" tabindex="-1" role="dialog" aria-labelledby="NewCategoryLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div id="modalContent" class="modal-content">

        <partial name="_CreateCategory" model="Model.CategoryModel" />

    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
<div class="modal fade" id="ResultCategory" tabindex="-1" role="dialog" aria-labelledby="ResultCategoryLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div id="content" class="modal-content">
        <partial name="_CategoryResult" model="Model.CategoryModel" />
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

So I need help to get hide the save modal and show another modal with return data


Solution

  • I solve the problem actually the problem was in one line in ajax code So all the code in controller and the view is correct and the line data type must be deleted the line is

     dataType: "json"
    

    When I deleted this line the code is working Well Thanks for every one