How to clear form data after saving to database? via Ajax . net mvc

Asked

Viewed 2,976 times

2

after saving an object in the database, the view continues to show the fields filled!

<fieldset>
<legend>Endereco:</legend>

    @Html.ValidationSummary()
    @Html.HiddenFor(e => e.CodigoPessoa, new { id = "Pessoa", name = "Pessoa" })
    @Html.Label("Cep: ")
    @Html.TextBoxFor(e => e.CEP, new { maxlength = "9", id = "Cep", name = "Cep", onchange = "findCEP()" })
    <br />
    @Html.Label("Endereco: ")
    @Html.TextBoxFor(e => e.DescricaoEndereco, new { maxlength = "50", id = "Endereco", name = "Endereco" })       
    <br />
    @Html.Label("Número: ")
    @Html.TextBoxFor(e => e.Numero, new { maxlength = "50", id = "Numero", name = "Numero" })       
    <br />
    @Html.Label("Complemento: ")
    @Html.TextBoxFor(e => e.Complemento, new { maxlength = "50", id = "Complemento", name = "Complemento" })      
    <br />
    @Html.Label("Bairro: ")
    @Html.TextBoxFor(e => e.Bairro, new { maxlength = "50", id = "Bairro", name = "Bairro" })     

    <br />
    @Html.Label("Cidade: ")
    @Html.TextBoxFor(e => e.Cidade, new { maxlength = "40", id = "Cidade", name = "Cidade" })   
    <br />
    @Html.Label("UF: ")
    @Html.DropDownListFor(e => e.UF, Model.UFList, new { id = "UF", name = "UF" })      
    <br />

function adicionarEndereco() {//Função Ajax  que obtem os valores dos campos e joga na action via post

    var codigoPessoa = document.getElementById("CodigoPessoa").value;
    var cep = document.getElementById("Cep").value;
    var endereco = document.getElementById("Endereco").value;
    var numero = document.getElementById("Numero").value;;
    var complemento = document.getElementById("Complemento").value;
    var bairro = document.getElementById("Bairro").value;
    var cidade = document.getElementById("Cidade").value;
    var temp = document.getElementById("UF");
    var uf = temp.options[temp.selectedIndex].value;

    $.ajax(
        {
            type: "POST",
            url: "/Master/CadastrarEndereco",
            data: {
                CodigoPessoa: codigoPessoa,
                Cep: cep,
                DescricaoEndereco: endereco,
                Numero: numero,
                Complemento: complemento,
                Bairro: bairro,
                Cidade: cidade,
                UF: uf,


            },
            success: function (data) {

                $("#endereco").html(data);
                //limpaForm();
            },


        });
}

   [HttpPost]
    public PartialViewResult CadastrarEndereco(SuperViewModel enderecoVM)  //action que salva o objeto obtido na view e enviado via ajax
    {
        if (string.IsNullOrEmpty(enderecoVM.Bairro))
            ModelState.AddModelError("Bairro", "Bairro é obrigatório");
        if (ModelState.IsValid)
        {
            var endereco = Extentions.MapearEndereco(enderecoVM);
            EnderecoRepositorio.Cadastrar(endereco);
            EnderecoRepositorio.Commit();
        }
        var dados = new SuperViewModel();//crio outro objeto para a view soh com as minhas dropdownlist e os dados da minha grid
        dados.UFList = Extentions.ObterUF();
        dados.Enderecos = EnderecoRepositorio.ObterEnderecoPorPessoa(enderecoVM.CodigoPessoa);
        return PartialView("_EnderecoFields", dados);
    }
  • If I return to Partialview without the object will break ! in the data object I have a dropdownlist clicking on the page and a enumerable for a grid that tbm use on the page!

  • may mount an SSCCE (http://sscce.org/) in the Dotnetfiddle (https://dotnetfiddle.net/)?

  • Have you ever considered using Dataannotations to say that the field is required? So you don’t need to use that IF in his action.

1 answer

2

You can use the following line to reset the form automatically after return from Ajax:

$('#id_do_form').each (function(){
    this.reset();
});

Your code would look like this:

$.ajax({
    type: "POST",
    url: "/Master/CadastrarEndereco",
    data: {
        CodigoPessoa: codigoPessoa,
        Cep: cep,
        DescricaoEndereco: endereco,
        Numero: numero,
        Complemento: complemento,
        Bairro: bairro,
        Cidade: cidade,
        //UF: uf, Nessa linha não é necessário a utilização da ","
        UF: uf
    },
    success: function (data) {
        $("#endereco").html(data);
        $('#id_do_form').each (function(){
            this.reset();
        });
    },
});

Example:

function iniciar(){
  document.getElementById("CodigoPessoa").value = "teste";
  document.getElementById("Cep").value = "teste";
  document.getElementById("Endereco").value = "teste";
  document.getElementById("Numero").value = "teste";
  document.getElementById("Complemento").value = "teste";
  document.getElementById("Bairro").value = "teste";
  document.getElementById("Cidade").value = "teste";
  document.getElementById("UF").value = "teste";
}

function limpar(){
  $('#teste').each (function(){
    this.reset();
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="teste" name="teste">
  <input type="text" id="CodigoPessoa"><br/>
  <input type="text" id="Cep"><br/>
  <input type="text" id="Endereco"><br/>
  <input type="text" id="Numero"><br/>
  <input type="text" id="Complemento"><br/>
  <input type="text" id="Bairro"><br/>
  <input type="text" id="Cidade"><br/>
  <select id="UF">
    <option value=""></option>
    <option value="teste">teste</option>
  </select><br/><br/>
  
  <input type="button" onclick="iniciar()" value="Preencher">
  <input type="button" onclick="limpar()" value="Limpar">
</form>


** EDIT **


I usually do this in PHP, particularly never messed with ASP so I can’t help much in this case.... but I’ll show you how I usually do in the PHP, who knows best how to proceed in the ASP

PHP

//Realizo as validações necessárias no lado do servidor antes de incluir ou excluir ou alterar....

function Incluir(){
    $con = new cmd_SQL(); //Abro conexão com o bd utilizando minhas conexões PHP

    setlocale(LC_CTYPE,"pt_BR"); //Seto a localização

    $db['tab']="tabela";
    $db['campos']="campos";
    $db['values']= $valores;

    if ($con->incluir($db)){ //Função criada em PDO para incluir
        echo "1"; //Se não houver nenhum erro na inclusão dos dados retorno 1
    }else{
        echo "0"; //Se houver erro na inclusão dos dados retorno 0
    }
}

function Excluir(){
    $con = new cmd_SQL();
    setlocale(LC_CTYPE,"pt_BR");

    $db['tab']="tabela";
    $db['cond']="campos=".$valores;

    if ($con->excluir($db)){ //Função criada em PDO para excluir
        echo "1"; //Se não houver nenhum erro na exclusão dos dados retorno 1
    }else{
        echo "0"; //Se houver erro na exclusão dos dados retorno 0
    }
}

On the client side I get the return on Ajax, and work with him as follows:

$.ajax({
    type: "POST",
    url: "/Master/CadastrarEndereco",
    data: {
        //dados
    },
    success: function (data) {
        $("#endereco").html(data);
        //data se refere ao meu retorno*, se foi incluído ou não com sucesso
        if (data == 1){
            //Foi incluido com sucesso, ou seja, devo usar a função Reset...
            $('#id_do_form').each (function(){
                this.reset();
            });
        }else{
            //Não foi incluido com sucesso, ou seja, não faço nada...
        }
    },
});

[OBS] * The Return can be used from n ways, I usually use only as 0 for failure or 1 for success in recording...

  • Wouldn’t it be better document.getElementById("id_do_form").reset();

  • it clears the data until the time to validate the fields! a mandatory field , it clears everything and only gets the error message ("Required field"). I have tried so, in a way it worked ,more at the time of validating not so much! the data vanish! I need the data to remain in this action

  • I didn’t get it right @Hansmiller, the problem is yours validate? What do you mean, the data’s gone? If you can explain your problem better... @Tobymosque This alternative you’ve commented on is better Rs, I’m a fan of Nojquery

  • The form also checks and validates,see the Neighborhood field,it is mandatory not to accept null, if it receives from the view a null value, it returns a message at the top of the form stating that the field is required, If we implement this solution @Marcelo when the user is registering and forget the neighborhood field, the function will validate and show the msgem. and then clear the form leaving no information for the user in the fields.So he knows that he has forgotten a field and he must fill in the form.

  • So you want the error msg to keep appearing... you want to clear the form, but the error messages appear correct?

  • following using this function! @Marcelobonifazio and using the form to register ,works well! pq vc register and at the end of the action clear all your fields! When validating a field the error message will appear and supposedly the form that the user filled will disappear! so these are the cucumbers I’m trying to unroll

  • Wouldn’t have a logic to use this function only when the user saves the data in the database??? if it doesn’t save the form doesn’t clear the form

  • So, how do you return your data after successfully saving, and after giving error?

  • take a look at the controller, action

  • everything depends on what comes in the return of your action @Hansmiller, I edited it into my code as I usually do on PHP, see if you can adapt to ASP

  • I’m sorry I didn’t answer ! I didn’t have time was worth @Marcelo for the tip! I applied logic and it worked

  • @Hansmiller :)

Show 7 more comments

Browser other questions tagged

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