Refresh ajax mvc core page

Asked

Viewed 719 times

3

I need to close a modal, and refresh the page, I’m doing this way:

 function closeModal() {
        $('#myModal').modal('hide');
        location.reload();
    }

But the first time it doesn’t work, and then it works normal, does anyone know why? Or some other code that can update, modal information, are included by an AJAX function, that works, need only update after closing the modal.

 <a href="#" onclick="SalvarItens(); closeModal();" class="btn btn-primary btn-sm">Gravar Item</a>

I save the function and then close the modal. What is happening that might be happening this strange behavior.

Edit, in the code: For example this is the save function:

function SalvarItens() {
    var idItem = $("#idItem").val();

    if (idItem == 0) {
        var dataInicio = $("#txtHoraInicio").val();
        var dataFim = $("#txtHoraFim").val();
        var tipoLimite = $("#txtTipoLimite").val();
        var limiteAcessos = $("#txtLimiteAcessos").val();
        var cbSeg = $('#cbSeg').prop('checked');
        var cbTer = $('#cbTer').prop('checked');
        var cbQua = $('#cbQua').prop('checked');
        var cbQui = $('#cbQui').prop('checked');
        var cbSex = $('#cbSex').prop('checked');
        var cbSab = $('#cbSab').prop('checked');
        var cbDom = $('#cbDom').prop('checked');
        var cbFer = $('#cbFer').prop('checked');
        var idHorario = $("#idHorario").val();
        var url = "/HorariosItens/SalvarItens";

        $.ajax({
            url: url
            , data: { HoraInicio: dataInicio, HoraFim: dataFim, Seg: cbSeg, Ter: cbTer, Qua: cbQua, Qui: cbQui, Sex: cbSex, Sab: cbSab, Dom: cbDom, Fer: cbFer, Tipolimite: tipoLimite, Limiteacessos: limiteAcessos, HorarioId: idHorario }
            , type: "POST"
            , datatype: "html"
            , success: function (data) {
                if (data.resultado > 0) {
                    ListarItens(idHorario);
                }
            }
        });
    } else {
        var dataInicio = $("#txtHoraInicio").val();
        var dataFim = $("#txtHoraFim").val();
        var tipoLimite = $("#txtTipoLimite").val();
        var limiteAcessos = $("#txtLimiteAcessos").val();
        var cbSeg = $('#cbSeg').prop('checked');
        var cbTer = $('#cbTer').prop('checked');
        var cbQua = $('#cbQua').prop('checked');
        var cbQui = $('#cbQui').prop('checked');
        var cbSex = $('#cbSex').prop('checked');
        var cbSab = $('#cbSab').prop('checked');
        var cbDom = $('#cbDom').prop('checked');
        var cbFer = $('#cbFer').prop('checked');
        var idHorario = $("#idHorario").val();

        var url = "/HorariosItens/EditarItem";

        $.ajax({
            url: url
            , data: { HoraInicio: dataInicio, HoraFim: dataFim, Seg: cbSeg, Ter: cbTer, Qua: cbQua, Qui: cbQui, Sex: cbSex, Sab: cbSab, Dom: cbDom, Fer: cbFer, Tipolimite: tipoLimite, Limiteacessos: limiteAcessos, HorarioId: idHorario, ItemId: idItem }
            , type: "POST"
            , datatype: "html"
            , success: function (data) {
                if (data.resultado > 0) {
                    ListarItens(idHorario);
                }
            }
        });
    }

}
This is the Listaritens:

function ListarItens(idHorario) {

    var url = "/HorarioItem/Create";

    $.ajax({
        url: url
        , type: "GET"
        , data: { id: idHorario }
        , datatype: "html"
        , success: function (data) {
            var divItens = $("#divItens");
            divItens.empty();
            divItens.show();
            divItens.html(data);
            $("#idItem").val("0");
            $("#idHorario").val(idHorario);
            //$('#myModal').modal('hide');
            
        }
    });
}

This is the code that saves:

  public ActionResult EditarItem(string HoraInicio, string HoraFim, bool Seg, bool Ter, bool Qua, bool Qui, bool Sex, bool Sab, bool Dom, bool Fer, int Tipolimite, int Limiteacessos, int HorarioId, int ItemId)
        {
            var item = new HorariosItens()
            {
                HoraFim = HoraFim,
                HoraInicio = HoraInicio,
                Seg = Seg,
                Ter = Ter,
                Qua = Qua,
                Qui = Qui,
                Sex = Sex,
                Sab = Sab,
                Dom = Dom,
                Fer = Fer,
                Tipolimite = Tipolimite,
                Limiteacessos = Limiteacessos,
                HorarioId = HorarioId,
                Id = ItemId
            };

            try
            {
                _context.Entry(item).State = EntityState.Modified;
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return Json(new { Resultado = item.Id });
        }

It includes, edits, and deletes, it only has hours that does not update, and has hours that updates.

Edit HTML:

div class="form-group">
<input type="button" value="Incluir Itens" onclick="abreModal();" class="btn btn-info btn-sm" />
</div>
<form method="post" id="createform">

  @if (Model.Message != null) {
  <div class="alert alert-info alert-dismissable" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="close">
                <span aria-hidden="true">&times;</span>
            </button> @Model.Message
  </div>
  }
  <input type="hidden" asp-for="HorariosVM.Horarios.Id" />
  <div class="col-md-10">
    <table class="table table-responsive" id="tabela">
      <thead>
        <tr>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].HoraInicio)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].HoraFim)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Seg)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Ter)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Qua)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Qui)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Sex)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Sab)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Dom)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Fer)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Tipolimite)
          </th>
          <th>
            @Html.DisplayNameFor(model => model.HorariosItens[0].Limiteacessos)
          </th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        @foreach (var item in Model.HorariosItens) {
        <tr>
          <td>
            @Html.DisplayFor(modelItem => item.HoraInicio)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.HoraFim)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Seg)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Ter)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Qua)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Qui)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Sex)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Sab)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Dom)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Fer)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Tipolimite)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Limiteacessos)
          </td>
          <td>
            <a href="#" onclick="EditarItem(@item.Id);abreModal();" class="btn btn-primary btn-sm">Alterar</a>
            <a href="#" onclick="ExluirItem1(@item.Id);" class="btn btn-danger btn-sm">Excluir</a> @*
            <a asp-page="./Edit" class="btn btn-success btn-sm" asp-route-id="@item.Id">Editar</a>
            <button asp-page-handler="Delete" asp-route-id="@item.Id" class="btn btn-danger btn-sm">Excluir</button>*@
          </td>
        </tr>
        }
      </tbody>
    </table>
  </div>
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-body">
          <div class="row">
            <div class="col-md-12">
              <div class="row form-group">
                <div class="col-md-6">
                  <div class="form-group">
                    <div class="col-md-9">
                      <label class="control-label">Hora Inicio</label>
                      <input type="time" class="form-control" id="txtHoraInicio" />
                    </div>
                  </div>
                  <br />
                  <div class="form-group">
                    <div class="col-md-9">
                      <label class="control-label">Hora Fim</label>
                      <input type="time" class="form-control" id="txtHoraFim" />
                    </div>
                  </div>
                  <br />
                  <div class="form-group">
                    <div class="col-md-9">
                      <label class="control-label">Tipo Limite</label>
                      <input id="txtTipoLimite" class="form-control" type="text" />
                    </div>
                  </div>
                  <br />
                  <div class="form-group">
                    <div class="col-md-9">
                      <label class="control-label">Limite de Acesso</label>
                      <input id="txtLimiteAcessos" type="text" class="form-control" />
                    </div>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="form-group">
                    <div class="col-md-10">
                      <div class="checkbox">
                        <input type="checkbox" id="cbSeg" />
                      </div>
                      <label class="control-label">Segunda</label>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="col-md-10">
                      <div class="checkbox">
                        <input type="checkbox" id="cbTer" />
                      </div>
                      <label class="control-label">Terça</label>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="col-md-10">
                      <div class="checkbox">
                        <input type="checkbox" id="cbQua" />
                      </div>
                      <label class="control-label">Quarta</label>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="col-md-10">
                      <div class="checkbox">
                        <input type="checkbox" id="cbQui" />
                      </div>
                      <label class="control-label">Quinta</label>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="col-md-10">
                      <div class="checkbox">
                        <input type="checkbox" id="cbSex" />
                      </div>
                      <label class="control-label">Sexta</label>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="col-md-10">
                      <div class="checkbox">
                        <input type="checkbox" id="cbSab" />
                      </div>
                      <label class="control-label">Sabado</label>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="col-md-10">
                      <div class="checkbox">
                        <input type="checkbox" id="cbDom" />
                      </div>
                      <label class="control-label">Domingo</label>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="col-md-10">
                      <div class="checkbox">
                        <input type="checkbox" id="cbFer" />
                      </div>
                      <label class="control-label">Feriado</label>
                    </div>
                  </div>

                </div>
              </div>
              <div class="form-group">
                <a href="#" onclick="closeModal();" class="btn btn-primary btn-sm">Gravar Item</a>
                <a href="#" onclick="fecha();" class="btn btn-danger btn-sm">Fechar</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</form>

Create it updates, but it doesn’t let you do any more functions. inserir a descrição da imagem aqui

  • Do you want to update the page and what do you expect from it? Does modal close? What happens after you pass Location.Reload(); Any output in the browser console?

  • I need that when closing the modal, update the table, the modal closes, but not always update the table.

  • And why when closing the modal you do not call an ajax to persist the data in the table? It makes no sense you close a modal, gives refresh on the page and it insert data in the table.

  • in ajax, it calls the function to change/edit/delete the data, and it does this, it just doesn’t update.

  • So your problem is certainly in c#. Finally you call Savechanges(); ?

  • I am debugging the code, the problem is in the ajax functions, by the way, the problem that even informing in the console.log(data.result) it is right, there is no reason for it not enter the date sucess.result.

  • @Netinhosantos happens that usually the first time he does not enter the sucess of the function, you know me tell pq this happens ? Debugging the code even if it is done successfully, it does not enter and therefore does not update the page as it has to update.

  • Post your ajax code.

  • @Netinhosantos I edited with the codes.

  • It may be a competition problem onclick="Save items(); closeModal();" you are calling two functions at the click of the button and this does not guarantee that it hides the modal and reloads the page after the submission in the Save items method().

  • But how can I close then the modal without giving this problem ?

  • Really I did the test, delete, change and edit without problems, but I need to close the modal, in case if I take the closeModal() I can only include once, and change it, it changes, but I have to close the modal, for it update.

Show 7 more comments

2 answers

1

Change the call sequence to arrange the execution of commands in the order you want. And forget the page Reload because it makes no sense in that context.

On the close button invoke only the closeModal()

<a href="#" onclick="closeModal();" class="btn btn-primary btn-sm">Gravar Item</a>

In the closeModal() call the SalvarItens()

function closeModal() {            
   SalvarItens();            
}

And in the ListarItens() give a Dispose in your modal

function ListarItens(idHorario) {
    $('#myModal').modal('dispose');
    var url = "/HorarioItem/Create";

    $.ajax({
        url: url
        , type: "GET"
        , data: { id: idHorario }
        , datatype: "html"
        , success: function (data) {
            var divItens = $("#divItens");
            divItens.empty();
            divItens.show();
            divItens.html(data);
            $("#idItem").val("0");
            $("#idHorario").val(idHorario);
        }
    });
}
  • In the form of Edit this way worked, but in create did not work, it opens the modal, it includes, updates, but it is as if the modal had opened, until I created the functions again, and put another name, to separate from Edit, and create.

  • I still can’t understand why you want to reload the page

  • In vdd i n need to reload the page, I need to update the table in create, and this is not happening.In Edit I reload the page, which was the best way I found, now in create, I’m not getting, it looks as if the modal n was closed, but it includes in the bank.

  • Include your view html in the question

  • I updated the question with HTML. Remembering that I work with Pagerazor and . net core

  • I tried that way you edited, but it didn’t work.

  • With Dispose it returns me the following error: Uncaught Typeerror: data[option] is not a Function at Htmldivelement.Eval

  • can be a matter of version and leaving with the Hide?

Show 3 more comments

1


From what I understand, you want to save/edit an item and the list to be updated, below follows an example of how you can do:

In the example, after saving/editing the list is loaded again.

I’m not sure what the architecture of your project looks like, so you’ll probably have to make adjustments.

The whole code of the example is available in this repository

As for closing the modal and the background turn gray, when the modal is tightening it adds a class in the body. I found this reply in the ONLY that asks to do so to close it

$('#your-modal-id').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();

View Index:

@{
    ViewData["Title"] = "Setores";
}
<div class="text-center">
    <h2>Setores</h2>
</div>

<button type="button" class="btn btn-add-new" onclick="carregaCreate()" data-toggle="modal" data-target="#myModal">Criar novo setor</button>

<div class="row">
    <div class="col-md-12">
        <div id="lista"></div>
    </div>
</div>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div id="corpoModal"></div>
        </div>
    </div>
</div>

@section scripts{
    <script src="~/js/Aplicacao/Setor/index.js"></script>
}

View _Create:

@model ProjetoBase.ViewModel.Setor.CreateSetorViewModel

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"></span></button>
    <h4 class="modal-title">Adicionar setor</h4>
</div>
<div class="modal-body">
    <div class="row">
        <form id="formCreate">

            <div class="col-md-12">
                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Nome" class="control-label"></label>
                        <input asp-for="Nome" class="form-control" />
                        <span asp-validation-for="Nome" class="text-danger"></span>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Sigla" class="control-label"></label>
                        <input asp-for="Sigla" class="form-control" />
                        <span asp-validation-for="Sigla" class="text-danger"></span>
                    </div>
                </div>
            </div>

            <div class="col-md-12">
                <div class="funkyradio">
                    <div class="col-md-3">
                        <div class="form-group">
                            <div class="funkyradio-success">
                                <input type='checkbox' checked asp-for="IsAtivo" />
                                <label asp-for="IsAtivo"></label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </form>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
    <input type="button" id="btnCreate" value="Adicionar" onclick="createSetor()" class="btn btn-default" />
</div>    

View _Lista:

@model IEnumerable<ProjetoBase.ViewModel.Setor.ViewSetorViewModel>

@if (Model.Count() <= 0)
{
    <span>Não há setores cadastrados</span>
}
else
{
    <table id="tableSetores" class="display table table-condensed table-hover" style="width:100%">
        <thead>
            <tr>
                <th class="text-center">
                    @Html.DisplayNameFor(model => model.IsAtivo)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Nome)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Sigla)
                </th>
                <th class="text-center">
                    Editar
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td class="text-center">
                        @if (item.IsAtivo)
                        {
                            <span class="fa fa-2x fa-check"></span>
                        }
                        else
                        {
                            <span class="fa fa-2x fa-times"></span>
                        }
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Nome)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Sigla)
                    </td>
                    <td class="text-center">
                        <i onclick="carregaUpdate(@item.SetorId)" class="fa fa-2x fa-pencil blue-color" data-toggle="modal" data-target="#myModal"></i>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}

View _Update:

@model ProjetoBase.ViewModel.Setor.UpdateSetorViewModel

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"></span></button>
    <h4 class="modal-title"></h4>
</div>
<div class="modal-body">
    <div class="row">
        <form id="formUpdate">
            <input asp-for="SetorId" type="hidden" />

            <div class="col-md-12">
                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Nome" class="control-label"></label>
                        <input asp-for="Nome" class="form-control" />
                        <span asp-validation-for="Nome" class="text-danger"></span>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Sigla" class="control-label"></label>
                        <input asp-for="Sigla" class="form-control" />
                        <span asp-validation-for="Sigla" class="text-danger"></span>
                    </div>
                </div>
            </div>

            <div class="col-md-12">
                <div class="funkyradio">
                    <div class="col-md-3">
                        <div class="form-group">
                            <div class="funkyradio-success">
                                <input type='checkbox' asp-for="IsAtivo" />
                                <label asp-for="IsAtivo"></label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </form>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
    <input type="button" id="btnUpdate" value="Atualizar" onclick="updateSetor()" class="btn btn-default" />
</div>

Index Avascript:

$(document).ready(function () {
    lista()
});

function createSetor() {
    var objeto = $("#formCreate").serialize();
    $.ajax({
        url: "/Setores/Create",
        type: "POST",
        data: objeto,
        datatype: "json",
        success: function (data) {

            if (data.MensagemSucesso != undefined) {
                notificaSucesso(data.MensagemSucesso)
                $("#corpoModal").html("");

                $('#myModal').modal('hide')
                lista();
            } else {
                notificaFalha(data.MensagemErro)
            }

        }
    });
}

function updateSetor() {
    var objeto = $("#formCreate").serialize();
    $.ajax({
        url: "/Setores/Update",
        type: "POST",
        data: objeto,
        datatype: "json",
        success: function (data) {

            if (data.MensagemSucesso != undefined) {
                notificaSucesso(data.MensagemSucesso)
                $("#corpoModal").html("");

                $('#myModal').modal('hide')
                lista();
            } else {
                notificaFalha(data.MensagemErro)
            }

        }
    });
}

function carregaCreate() {
    $("#corpoModal").load("Setores/CarregaCreate");
}

function carregaUpdate(id) {
    $("#corpoModal").load("Setores/CarregaUpdate/" + id);
}

function lista() {
    $("#lista").load("setores/lista", function () {
    });
}

Controller:

public class SetoresController : Controller
{
    private readonly ISetorService _setorService;
    public SetoresController(ISetorService setorService)
    {
        _setorService = setorService;
    }

    [HttpGet]
    public IActionResult Index() => View();

    [HttpGet]
    public IActionResult CarregaCreate() => PartialView("_Create");

    [HttpPost]
    public IActionResult Create(CreateSetorViewModel viewModel)
    {
        if (!ModelState.IsValid)
            return Json(new { MensagemErro = ModelState.DisplayErros() });

        Setor setor = Mapper.Map<Setor>(viewModel);

        List<StatusValidacaoEnum> status = _setorService.ValidaSetor(setor);

        if (status.Count > 0)
            return Json(new { MensagemErro = status.DisplayDescriptionsToViewModel() });

        if (_setorService.Insert(setor))
            return Json(new { MensagemSucesso = "Setor incluso com sucesso" });
        else
            return Json(new { MensagemErro = "Erro ao adicionar setor" });
    }

    [HttpGet]
    public IActionResult CarregaUpdate(int id)
    {
        Setor setor = _setorService.SelectById(id);

        if (setor == null)
            return PartialView("_Create");

        UpdateSetorViewModel viewModel = Mapper.Map<UpdateSetorViewModel>(setor);

        return PartialView("_Update", viewModel);
    }

    [HttpPost]
    public IActionResult Update(UpdateSetorViewModel viewModel)
    {
        if (!ModelState.IsValid)
            return Json(new { MensagemErro = ModelState.DisplayErros() });

        Setor setor = Mapper.Map<Setor>(viewModel);

        List<StatusValidacaoEnum> status = _setorService.ValidaSetor(setor);

        if (status.Count > 0)
            return Json(new { MensagemErro = status.DisplayDescriptionsToViewModel() });

        if (_setorService.Update(setor))
            return Json(new { MensagemSucesso = "Setor atualizado com sucesso" });
        else
            return Json(new { MensagemErro = "Erro ao atualizar setor" });
    }

    [HttpGet]
    public IActionResult Lista()
    {
        List<ViewSetorViewModel> viewModels = Mapper.Map<List<ViewSetorViewModel>>(_setorService.Select());
        return PartialView("_Lista", viewModels);
    }
}
  • It updates the table, but is as if n has closed the modal, I will post the image to you see how it looks.

  • @marianac_costa, updated the answer

  • The funny thing is that running straight on visual, it worked, and out no, but after putting the code to close the modal q vc updated the answer, it worked, thanks again.

Browser other questions tagged

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