Error creating modal window with jQuery in ASP.NET MVC

Asked

Viewed 597 times

0

I am trying to create a modal window with registration deletion confirmation and avoid having to create a View only to present a message, but something is not loading right. I tried to create the window with both Display and Modal, but it’s still not working, I also checked the CSS Bundles to see if it’s not something with the references, but I didn’t detect the error if it’s 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>

Script jQuery

$(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

inserir a descrição da imagem aqui

_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>

2 answers

2

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

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

The.load function of jQuery loads the return content of a request into the element in question, in the case of the '#dialog'.

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

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


If you just want to delete the record by clicking the 'Delete' button in the dialog, just create a traditional jQuery ajax statement that requests the POST 'Delete' 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 }
        });
    });
});
  • Hello Renan, I want instead of loading a View load a Modal window that looks much better. On that line you quoted I was passing a parameter to the constructor method.

  • I get it. If you’ve done it, put the code here and mark the answer as resolution, to help people who pass through here ;)

  • 1

    Renan, posted the solution, just did not make the comments explaining in detail. I marked your reply as useful because it was also good. Sorry for the delay in answering. Thank you for your help!

1


This problem was solved with the help of a friend of the forum VBMANIA.COM, whose nick is KERPLUNK. I haven’t made the proper comments, but if you look closely, you can understand how it works. I hope this solution can help other people here on 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.