Modal not redirect when running Post

Asked

Viewed 1,388 times

1

I own a View where I open a Modal to register a new data. It is working perfectly. The problem is that when registering using this Modal, it redirects me to the pre-defined page in cController. However, I just need the Modal close, by clicking on Salvar.

In my Controller, I have the following method to save:

public ActionResult Adicionar()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Adicionar(ConstrutoraViewModel construtoraViewModel)
        {
            if (ModelState.IsValid)
            {
                _construtoraAppService.Adicionar(construtoraViewModel);
              //Faço o redirecionamento aqui, pois utilizo este método fora do modal também.
                return RedirectToAction("Index");
            }

            return View(construtoraViewModel);
        }

In itself Controller i do the redirect. However, I need it to continue, because I use it to perform the action Modal also.

My View registration is this way:

@model Sisco.Application.ViewModels.ConstrutoraViewModel

@{
    ViewBag.Title = "Adicionar Construtora";
}

@using (Html.BeginForm("Adicionar", "Construtora"))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <br /><br />
        @Html.ValidationSummary(true, "", new {@class = "text-danger"})
        <div class="form-group">
            <div class="row">
                @Html.LabelFor(model => model.Nome, new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Nome, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.Nome, "", new {@class = "text-danger"})
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="row">
                @Html.LabelFor(model => model.CNPJ, new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.CNPJ, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.CNPJ, "", new {@class = "text-danger"})
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="row">
                @Html.Label("DDD", new {@class = "control-label col-md-2"})
                <div class="col-md-1">
                    @Html.EditorFor(model => model.DDD, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.DDD, "", new {@class = "text-danger"})
                </div>
                @Html.Label("Telefone", new {@class = "control-label col-md-2", style = "width: 100px"})
                <div class="col-md-4">
                    @Html.EditorFor(model => model.Telefone, new {htmlAttributes = new {@class = "form-control", style = "width: 81%"}})
                    @Html.ValidationMessageFor(model => model.Telefone, "", new {@class = "text-danger"})
                </div>
                <div class="3"></div>
            </div>
        </div>


        <hr />


        <div class="form-group">
            <div class="row">
                @Html.Label("CEP", new { @class = "control-label col-md-2" })
                <div class="col-md-2">
                    @Html.EditorFor(model => model.Endereco.CEP, new { htmlAttributes = new { @class = "form-control", @id = "cepConstrutora" } })
                    @Html.ValidationMessageFor(model => model.Endereco.CEP, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-8"></div>
            </div>
        </div>

        <div class="form-group">
            <div class="row">
                @Html.LabelFor(model => model.Endereco.Bairro, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Endereco.Bairro, new { htmlAttributes = new { @class = "form-control", @id = "bairroConstrutora" } })
                    @Html.ValidationMessageFor(model => model.Endereco.Bairro, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>


        <div class="form-group">
            <div class="row">
                @Html.Label("Logradouro", new { @class = "control-label col-md-2" })
                <div class="col-md-4">
                    @Html.EditorFor(model => model.Endereco.Logradouro, new { htmlAttributes = new { @class = "form-control", @id = "enderecoConstrutora" } })
                    @Html.ValidationMessageFor(model => model.Endereco.Logradouro, "", new { @class = "text-danger" })
                </div>
                @Html.Label("Nº", new { @class = "control-label col-md-1" })
                <div class="col-md-1">
                    @Html.EditorFor(model => model.Endereco.Numero, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Endereco.Numero, "", new { @class = "text-danger" })
                </div>
                <div class="5"></div>
            </div>
        </div>


        <div class="form-group">
            <div class="row">
                @Html.LabelFor(model => model.Endereco.Complemento, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Endereco.Complemento, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Endereco.Complemento, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="row">
                @Html.Label("Estado", new { @class = "control-label col-md-2" })
                <div class="col-md-2">
                    @Html.EditorFor(model => model.Endereco.Estado, new { htmlAttributes = new { @class = "form-control", @id = "estadoConstrutora" } })
                    @Html.ValidationMessageFor(model => model.Endereco.Estado, "", new { @class = "text-danger" })
                </div>
                @Html.Label("Cidade", new { @class = "control-label col-md-2" })
                <div class="col-md-2">
                    @Html.EditorFor(model => model.Endereco.Cidade, new { htmlAttributes = new { @class = "form-control", @id = "cidadeConstrutora" } })
                    @Html.ValidationMessageFor(model => model.Endereco.Cidade, "", new { @class = "text-danger" })
                </div>
                <div class="5"></div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-2"></div>
            <div class="col-md-3">
                <input type="submit" value="Salvar" class="btn btn-primary" />
            </div>
            <div class="col-md-7">
                <a href="@Url.Action("Index", "Construtora")" cla class="btn btn-danger">
                    <span class="glyphicon glyphicon-plus-sign" />
                    Cancelar
                </a>
            </div>
        </div>
    </div>
}

And I’m calling the Modal with the View in this way:

    <div class="col-md-4" align="left">
                    @Html.ActionLink(" ", "Adicionar", "Construtora", new { href = "#myModal", data_toggle = "modal",
                                                                            @class = "btn btn-primary glyphicon glyphicon-plus-sign",
                                                                            @id = "btnAddConstrutora",
                                                                            @title="Adicionar Nova Construtora"
               })


<div class="modal fade bs-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Cadastrar Nova Construtora</h4>
            </div>
            <div class="modal-body">
                @Html.Partial("~/Views/Construtora/Adicionar.cshtml", new ConstrutoraViewModel());
            </div>
        </div>
    </div>
</div>

I thought about creating a similar new method, not taking the redirect. But that would be a rework, and yet, I don’t think that’s the best option.

Summary of the problem: I need that when executing the Post of Action in my Modal, do not update the page. Simply close the Modal.

  • I’m using Version 3.3.4 of Bootstrap
  • I think you should have put Ajax here. As there is no Javascript code, we have no way of knowing how the modal invocation is executed.

  • @Ciganomorrisonmendez did not understand his comment very well. However, the invocation of Modal is all in the code. I’m not using Javascript to call the modal. The actionLink that was calling the same.

2 answers

1

A suggestion is to create a method void to execute the adicionar, so it will not redirect after inserting, and for there to be code duplicity the method that redirects can call this method void and then do the directing.

1


Well, the best solution I’ve found so far is this:

I created a requisition Ajax, where I call the Modal for her, so:

  <div class="col-md-4" align="left">
                            @Html.ActionLink(" ", "Adicionar", "Construtora", null, new
                    {
                        id = "btnAddConstrutora",
                        @class = "btn btn-primary glyphicon glyphicon-plus-sign",
                        @title = "Adicionar Nova Construtora"
                    })
<div class="modal fade bs-example-modal-lg" id="dialogDiv" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div id="dialogContent"></div>
</div>


<script type="text/javascript">
    $(function () {

        //Optional: turn the chache off
        $.ajaxSetup({ cache: false });

        $('#btnAddConstrutora').click(function () {
            $('#dialogContent').load(this.href, function () {
                $('#dialogDiv').modal({
                    backdrop: 'static',
                    keyboard: true
                }, 'show');
                bindForm(this);
            });
            return false;
        });
    });

    function bindForm(dialog) {
        $('form', dialog).submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.success) {
                        $('#dialogDiv').modal('hide');
                        // Refresh:
                        // location.reload();
                    } else {
                        $('#dialogContent').html(result);
                        bindForm();
                    }
                }
            });
            return false;
        });
    }

</script>

And in my Controller I simply check if the request is coming from Ajax or not. In case you are, I know it’s mine Modal and do another treatment for it. In case, I’m not giving the Redirect. Thus remaining:

 public ActionResult Adicionar()
        {
            if (Request.IsAjaxRequest())
            {
                return View("_AdicionarModalPredio");
            }
            return View();
        }
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Adicionar(ConstrutoraViewModel construtoraViewModel)
    {
        if (ModelState.IsValid)
        {
            _construtoraAppService.Adicionar(construtoraViewModel);

            if (Request.IsAjaxRequest())
            {
                return Json(new { success = true });
            }
            return RedirectToAction("Index");
        }

        return View(construtoraViewModel);
    }

That way, I call one PartialView instead of View, only to treat the Layout.

  • If anyone has a better answer, I’ll be happy to meet.

Browser other questions tagged

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