close Bootstrap modal popup

0

I'm trying to close a modal bootstrap window with a url returned from the ActionResult, but for some reason it's not working:

This is my script:

    $('form').submit(function () {
    var $form = $(this);
    $.ajax({
        url: this.action,
        type: this.method,
        contentType: this.enctype,
        data: $(this).serialize(),
        success: function (result) {
            if (result.success) {
                $('#myModal').modal('hide');
                //Refresh
                //location.reload();
                $('#replacetarget').load(result.url);
            } else {
                $('#myModalContent').html(result);
                //bindForm();
            }
        }
    });
});

This is my ActionResult:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateForCategory(MaterialViewModel material, HttpPostedFileBase upload)
{

    material.Status = Status.Activo;
    material.FechaRegistro = DateTime.Today.Date;

    var materialDomain = Mapper.Map<MaterialViewModel, Material>(material);

    if (upload != null && upload.ContentLength > 0)
    {
        var imagen = new Imagen
        {
            Nombre = System.IO.Path.GetFileName(upload.FileName),
            TipoContenido = upload.ContentType
        };

        using (var reader = new System.IO.BinaryReader(upload.InputStream))
        {
            imagen.Contenido = reader.ReadBytes(upload.ContentLength);
        }

        materialDomain.Imagen = imagen;
    }

    _materialRepository.Create(materialDomain);


    string url = Url.Action("MaterialesPorCategoriaIndex", "CategoriaMateriales");

    return Json(new { success = true, url = url }, JsonRequestBehavior.AllowGet);
}

When you return the json value, a blank view with this text is displayed:

{"success": true, "url": "/ CategoryMaterials / MaterialsByCategoryIndex"}

This is my main view:

@model CategoriaMaterialViewModel
@{
    ViewBag.Title = "CategoriaMaterial";
}
<link href="~/Content/css/blockingwindow.css" rel="stylesheet" />

<div class="content clearfix">
    @Styles.Render("~/Content/MiBundle")
    @Styles.Render("~/Content/toastr")

    <div id="page-wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-17">
                    <h3>
                        <!-- class="page-header" -->
                        Lista de Materiales de: @Html.DisplayFor(x => x.Descripcion)
                    </h3>
                    <ol class="breadcrumb">
                        <li><a class="MenuBread" href='@Url.Action("Index", "Home")' data-toggle="tooltip" title="Inicio">Inicio</a></li>
                        <li class="active"><b>Lista de Materiales</b></li>
                    </ol>
                </div>

                <div class="panel panel-default">

                    @Html.HiddenFor(x => x.CategoriaId, new { @id = "categoriaId" })
                    <form class="form-horizontal">
                        <div class="form-group">
                            <div class="col-sm-9">
                                <a data-target='#myModal' href='@Url.Action("CreateForCategory", "CategoriasMateriales")' id="btnCreate" class="btn btn-info" role="button">Agregar Material</a>
                                <a href='@Url.Action("Index", "CategoriasMateriales")' class="btn btn-warning" role="button">Regresar a Categorías</a>
                            </div>
                        </div>
                    </form>

                    <div id="materialesPorCategoria"></div>
                </div>


            </div> <!-- /.row -->
        </div><!-- /.container-fluid -->
    </div> <!-- /.container-PAGE -->
</div>


@section Scripts {

    @Scripts.Render("~/bundles/toastr")
    @Scripts.Render("~/Content/MyScripts")
    @Scripts.Render("~/Content/TableScripts")
    @Html.Partial("_Toastr")
}

<script type="text/javascript" language="javascript" class="init">

    $('#btnCreate').click(function (e) {
        e.preventDefault();
        $('#btnCreate').attr('data-modal', '');
        $('#btnCreate').attr('data-toggle', 'modal');
        $('#myModalContent').load(this.href + '/' + $('#categoriaId').val(), function () {
            $('#myModal').modal({
                /*backdrop: 'static',*/
                keyboard: true
            }, 'show');

        });
        return false;
    });


    $('form').submit(function () {
        var $form = $(this);
        $.ajax({
            url: this.action,
            type: this.method,
            contentType: this.enctype,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    //Refresh
                    //location.reload();
                    //$('#replacetarget').load(result.url);
                } else {
                    $('#myModalContent').html(result);
                    //bindForm();
                }
            }
        });
    });

</script>

<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>

This is my Modal view:

@model MaterialViewModel

@{
    ViewBag.Title = "Nuevo material";
    Layout = null;
}

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Content/js/fileUpload.js"></script>
<link href="~/Content/css/fileUpload.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui.js"></script>
<link href="~/Content/popup/popupstyle.css" rel="stylesheet" />

<div class="modal-header modal-header-success">

    <h3 class="modal-title" style="text-align: center;">
        xxxxx
        <button type="button" class="close panelTitleTxt glyphicon glyphicon-remove landing-icon" data-dismiss="modal" aria-hidden="true"></button>
    </h3>
</div>

@using (Html.BeginForm("CreateForCategory", "CategoriasMateriales", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Styles.Render("~/Content/toastr")

        <br />

        <div class="form-horizontal">
            @Html.HiddenFor(x => x.CategoriaId)
            @Html.ValidationSummary(true, "", new {@class = "text-danger"})
            <div class="form-group">
                @Html.LabelFor(model => model.CategoriaId, htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})
                <div class="col-sm-8">
                    @Html.DropDownListFor(x => x.CategoriaId, Model.CategoriasMaterialViewModel, new {@class = "form-control", @disabled = "disabled"})
                    @Html.ValidationMessageFor(model => model.CategoriaId, "", new {@class = "label label-danger"})
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Descripcion, htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})
                <div class="col-sm-8">
                    @Html.EditorFor(model => model.Descripcion, new {htmlAttributes = new {@class = "form-control", maxlength = "200"}})
                    @Html.ValidationMessageFor(model => model.Descripcion, "", new {@class = "label label-danger"})
                </div>
            </div>

            <div class="form-group">
                @Html.Label("Imagen", htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})
                <div class="col-md-offset-0 col-sm-offset-0 col-sm-8">
                    <!-- image-preview-filename input [CUT FROM HERE]-->
                    <div class="input-group image-preview">
                        <input type="text" class="form-control image-preview-filename" disabled="disabled"> <!-- don't give a name === doesn't send on POST/GET -->
                        <span class="input-group-btn">
                            <!-- image-preview-clear button -->
                            <button type="button" class="btn btn-danger image-preview-clear" style="display: none;">
                                <span class="glyphicon glyphicon-remove"></span> Clear
                            </button>
                            <!-- image-preview-input -->
                            <div class="btn btn-info image-preview-input">
                                <span class="glyphicon glyphicon-folder-open"></span>
                                <span class="image-preview-input-title">Browse</span>
                                <input type="file" accept="image/png, image/jpeg, image/gif" name="upload" /> <!-- rename it -->
                            </div>
                        </span>
                    </div><!-- /input-group image-preview [TO HERE]-->
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-10">
                    <input class="btn btn-success" id="btnSave" type="submit" value="Guardar"/>
                    <input aria-hidden="true" class="btn btn-md btn-warning" data-dismiss="modal" id="btncancel" type="button" value="Cancelar"/>
                </div>
            </div>

            <div>
                @Scripts.Render("~/bundles/toastr")
                @Html.Partial("_Toastr")
            </div>
        </div>
    </div>
}

<script>
    $("form").removeData("validator");
    $("form").removeData("unobtrusiveValidation");
    $.validator.unobtrusive.parse("form");

    $('form').submit(function () {

        $('#myModal').on('hidden.bs.modal', function () {
            window.LoadMateriales();
        });
    });

    $('.modal').modal({
        keyboard: true,
        show: false
    });
    // Jquery draggable
    $('.modal-dialog').draggable({
        handle: ".modal-header"
    });
</script>

If anyone has any idea how to solve this, I would greatly appreciate your support.

    
asked by jose luis garcia 15.05.2016 в 00:50
source

2 answers

1

You forgot to pass the dataType parameter, which determines the type of data you are waiting for as an answer, in this case the value is json .

This would be the code:

$('form').submit(function () {
  var $form = $(this);
  $.ajax({
    url: this.action,
    type: this.method,
    contentType: this.enctype,
    dataType: 'json',
    data: $(this).serialize(),
    success: function (result) {
        if (result.success) {
            $('#myModal').modal('hide');
            //Refresh
            //location.reload();
            $('#replacetarget').load(result.url);
        } else {
            $('#myModalContent').html(result);
            //bindForm();
        }
    }
  });
});

jQuery documentation :

  

dataType (default: Intelligent Guess (xml, json, script, or html))

     

Type: String

     

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield to JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

    
answered by 15.05.2016 в 02:13
-2

Try to do result = JSON.parse(result) before doing if(result.success) .

    
answered by 11.06.2016 в 00:18