Модальное окно с формой не закрывается при отправке в MVC5 - PullRequest
0 голосов
/ 21 мая 2018

В главном окне есть модальная форма, которую я вызываю следующей кнопкой:

 <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#agregarProducto">Agregar Material </a>

modal

Код моего модального окнав моем основном виде есть следующее:

<div class="modal fade" id="agregarProducto">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">               
                <h5 class="modal-title">Agregar Material</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="alert alert-dismissible alert-info">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <strong>Tener en cuenta!</strong> <a> para agregar más de una unidad habilite</a><strong> agregar cantidad.</strong>
                </div>
                <form id="myForm">
                    <label>Agregar Cantidad</label> &nbsp;&nbsp;
                    <input type="checkbox" id="idcheckcantidad" />
                    <br />
                    <input type="text" class="form-control" name="cantidad" id="idcantidad" disabled="disabled" />
                    <br />
                    <label>Codigo Producto</label> &nbsp;&nbsp;
                    <input type="text" class="form-control" name="codigoproducto" id="idcodigoproducto" autofocus="true" />
                </form>
            </div>            
             <div class="modal-footer">
                <input type="submit" value="Agregar Material" class="btn btn-primary" id="btnSubmit" />
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>                
             </div>
         </div>
    </div>
</div>

в структуре заголовка моего html я ссылаюсь на следующее:

<script type="text/javascript" src="~/Scripts/jquery-1.12.4.min.js"></script>
    <link href="~/Content/bootstrap-superhero.min.css" rel="stylesheet" />
    <script src="~/Scripts/bootstrap.min.js"></script>

и мой javascript следующий:

 <script>
        $(document).ready(function () {
            $("#btnSubmit").click(function () {

                var myformdata = $("#myForm").serialize();

                $.ajax({
                    type: "POST",
                    url: "/Despachos/AgregarProducto",
                    data: myformdata,
                    success: function () {                     
                        $("#agregarProducto").hide();                       
                    }
                })
            })
        })
    </script>

и в моем BundleConfig у вас есть:

Bundle

Эта форма вызывает метод POST на моем контроллере ..

       [HttpPost]
        public ActionResult AgregarProducto(int codigoproducto, int? cantidad)
        {  
           return View();
        }

Проблема возникает, когда я нажимаю на отправку формы, это модальное окно не скрывается, хотя при установке точки останова в моем методе post оно выполняется

Почему я получаю такое поведение?Это первый раз, когда я работаю с модальными формами, какая-нибудь помощь для меня?

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

Запрос $.ajax HttpPost ожидает ответа, но вы возвращаете представление.

Если вы измените свою функцию $ .ajax на:

$.ajax({
    type: "POST",
    url: "/Despachos/AgregarProducto",
    data: myformdata,
    success: function () {
        $("#agregarProducto").hide();
    },
    error: function (xhr, text, error) {
        console.log(xhr.status + " => " + error);
    }
});

Вы должнысм. ошибку в консоли.

Если вы измените AgregarProducto на:

[HttpPost]
public ActionResult AgregarProducto(int codigoproducto, int? cantidad)
{  
    var jsonResult = "Json Result";
    return Json(jsonResult);
}

Ваш модал должен закрыться (если вы измените функцию успеха, как предложено в комментариях).

Если вы хотите вернуть вид, вам нужно найти другой путь;например, вернуть представление в виде строки из действия HttpPost как часть ответа Json или установить window.location.href = "Path/To/Controller/For/View"; в $.ajax success

0 голосов
/ 21 мая 2018

Если вы используете Bootstrap, я думаю, что ваш синтаксис отключен ... должно быть так:

$("#agregarProducto").modal('hide');
...