Error creating modal window with jQuery in ASP.NET MVC

0

I'm trying to create a modal window with confirmation for deleting the registry and avoid having to create a View only to display a message, but something is not loading right. I tried to create the window with both Display and Modal, but it still is not working, I also checked the CSS Bundles to see if it is not something with the references, but I did not detect the error if it is in the wrong script or css. >

View

@model IEnumerable<MvcModeloEmpresa.Dominio.Regiao>

@{
    ViewBag.Title = "Lista de Regiões";
}

<h2>Lista Regiões</h2>

<p>
    @Html.ActionLink("Cadastrar Nova", "Adicionar")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.RegiaoID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.RegiaoDescricao)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modeTeste => item.RegiaoID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.RegiaoDescricao)
            </td>
            <td>
                @Html.ActionLink("Editar", "Editar", new { id = item.RegiaoID }) |
                @Html.ActionLink("Detalhes", "Detalhes", new { id = item.RegiaoID }) |
                @Html.ActionLink("Deletar","", "", new { @class = "excluir", datacodigo = item.RegiaoID, href="#" })
            </td>
        </tr>
    }

</table>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryui")
}

<div id="dialogo" style="display:none">
    <p>Confirmar exclusão de registro?</p>
</div>

jQuery script

$(document).ready(function () {
	$(".excluir").click(function () {
		var codigo = $(this).attr("datacodigo");
		$("#dialogo").dialog({
			title: "Aviso!",
			height: 200,
			width: 300,
			modal: true,
			resizable: false,
			buttons: {
				"Excluir": function () {
					$("#dialogo").load("/Regiao/Deletar/" + codigo);
				},
				"Cancelar": function () {
					$(this).dialog("close");
				}
			},
			show: { effect: "blind", duration: 400 }
		});
	})
})

Bundles

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>

    <h2>Menu Sistema</h2>
    <ul>
        <li>@Html.ActionLink("Regiões", "Index", "Regiao")</li>
        <li>@Html.ActionLink("Territórios", "Index", "Territorio")</li>
    </ul>

    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")    
    @RenderSection("scripts", required: false)
</body>
</html>
    
asked by anonymous 26.09.2015 / 02:58

2 answers

1

This problem has been solved with the help of a friend of the VBMANIA.COM forum, whose nickname is KERPLUNK. I did not give the necessary comments, but analyzing well gives you to understand how it works. I hope this solution can help other people here in the forum as well.

Script

$(document).ready(function () {

    $(".excluir").click(function () {

        var codigo = $(this).attr("datacodigo");

        $("#modal").load("/Regiao/Deletar/" + codigo)
                   .attr("title", "Confirmação de Exclusão")
                   .dialog({
                       modal: true,
                       resizable: false
                   });
    });

    $("#btnDelete").click(function () {

        $.post("/Regiao/Deletar/", $("#formDelete").serialize())
         .done(function () {
             window.location.href = "/Regiao/Index";
         });

        $("#modal").dialog("close");
    });

    $("#btnClose").click(function () {
        $("#modal").dialog("close");
    });
})

View to load dialog window

@model MvcModeloEmpresa.Dominio.Regiao

<form id="formDelete">
    @Html.AntiForgeryToken()

    <p>Excluir a região <strong>@Html.DisplayFor(model => model.RegiaoDescricao)</strong>?</p>

    @Html.HiddenFor(model => model.RegiaoID)
</form>

<hr />

<div>
    <button class="ui-state-default ui-corner-all" id="btnDelete">Excluir</button>
    <button class="ui-state-default ui-corner-all" id="btnClose">Cancelar</button>
</div>

@Scripts.Render("~/bundles/jqueryui") @*Para carregar novamente os scripts após o carregamento do documento html*@

View Index.cshtml to list regions

@model IEnumerable<MvcModeloEmpresa.Dominio.Regiao>
@{
    ViewBag.Title = "Lista de Regiões";
}

<h2>Regiões</h2>

<p>
    @Html.ActionLink("Cadastrar Nova", "Adicionar")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.RegiaoID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.RegiaoDescricao)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modeTeste => item.RegiaoID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.RegiaoDescricao)
            </td>
            <td>
                @Html.ActionLink("Editar", "Editar", new { id = item.RegiaoID }) |
                @Html.ActionLink("Detalhes", "Detalhes", new { id = item.RegiaoID }) |
                @Html.ActionLink("Deletar", String.Empty, null, new { @class = "excluir", datacodigo = item.RegiaoID, href = "#" })                
            </td>
        </tr>
    }

</table>

<div id="modal">

</div>
    
22.01.2016 / 21:03
2

If your goal is to avoid making a view to confirm the deletion, why are you loading the contents of the view into the dialog, in this line below?

$("#dialogo").load("/Regiao/Deletar/" + codigo);

The '.load' function of jQuery loads the contents of the return of a request into the element in question, in this case '#dialogo'.

I think the 'Delete' action returns the 'Delete.cshtml' view, so it is not working.

By default MVC creates a POST 'Delete' action, which actually deletes the record.

If you just want to delete the record when you click the 'Delete' button in the dialog, just create a traditional jQuery ajax statement that requests the 'Delete' POST action:

$.ajax({
    url: "/Regiao/Deletar/" + codigo,
    method: "POST",
    success: function (retorno) {
        alert("Registro excluído com sucesso!");
    }
});

Your final code would be:

$(document).ready(function () {
    $(".excluir").click(function () {
        var codigo = $(this).attr("datacodigo");
        $("#dialogo").dialog({
            title: "Aviso!",
            height: 200,
            width: 300,
            modal: true,
            resizable: false,
            buttons: {
                "Excluir": function () {
                    $.ajax({
                        url: "/Regiao/Deletar/" + codigo,
                        method: "POST",
                        success: function (retorno) {
                            alert("Registro excluído com sucesso!");
                        }
                    });
                },
                "Cancelar": function () {
                    $(this).dialog("close");
                }
            },
            show: { effect: "blind", duration: 400 }
        });
    });
});
    
05.01.2016 / 02:08