Update page ajax mvc core

2

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

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

But the first time it does not 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, which works, I just need to update after closing 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 may be happening this strange behavior.

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

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 ListarItems:

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 it does not update, and has hours that it 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 no longer has any function.

    
asked by anonymous 04.06.2018 / 21:53

2 answers

1

I understand that you want to save / edit an item and that the list is updated, here's an example of how you can do it:

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

I'm not sure how the architecture of your project is, so you'll probably have to make adjustments.

The entire sample code is available at repository

As for closing the modal and the background becomes gray, when the modal is tightening it adds a class in the body. I found this response in the OS it 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 _List:

@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 javaScript:

$(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);
    }
}
    
05.06.2018 / 19:13
1

Change the call sequence to organize the execution of the commands in the order you want. And forget the page reload because that does not make any sense in that context.

Close button invokes only closeModal()

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

In closeModal() call SalvarItens()

function closeModal() {            
   SalvarItens();            
}

And in 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);
        }
    });
}
    
05.06.2018 / 17:07