How to leave empty textbox after an Ajax request via Post?

5

I have a registration application in .Net MVC and I'm using Ajax to send the contents of Forms to my Action that registers, when I save the value of the fields, in my view the values are still visible in the fields not leaving blank , as would the standard. Please check my code:

    <div id="endereco">
    @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" })
    <br />
    @Html.Label("Complemento: ")
    @Html.TextBoxFor(e => e.Complemento, new { maxlength = "50", id = "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 />

<input type="button" value="Adicionar Endereco" onclick="adicionarEndereco()"/>
        <\div>
    function adicionarEndereco() {
    var codigoPessoa = $("#Pessoa").val();
    var cep = $("#Cep").val();
    var endereco = $("#Endereco").val();
    var numero = $("#Numero").val();
    var complemento = $("#Complemento").val();
    var bairro = $("#Bairro").val();
    var cidade = $("#Cidade").val();
    //var temp = document.getElementById("UF");
    var uf = $("#UF").val();  

    $.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);

            },


        });
}
          //Controller

                   [HttpPost]
    public PartialViewResult CadastrarEndereco(SuperViewModel enderecoVM)
    {
        if (ModelState.IsValid)
        {
            var endereco = Extentions.MapearEndereco(enderecoVM);
            EnderecoRepositorio.Cadastrar(endereco);
            EnderecoRepositorio.Commit();
        }
        var superVM = new SuperViewModel();
        superVM.UFList = Extentions.ObterUF();
        superVM.Enderecos = EnderecoRepositorio.ObterEnderecoPorPessoa(enderecoVM.CodigoPessoa);
        return PartialView("_EnderecoFields", superVM);
    }
    
asked by anonymous 02.02.2015 / 15:03

3 answers

4

You can do a function to clear the form and call it in success of ajax:

function limpaForm(){
    $("#Pessoa").val('');
    $("#Cep").val('');
    $("#Endereco").val('');
    $("#Numero").val('');
    $("#Complemento").val('');
    $("#Bairro").val('');
    $("#Cidade").val('');
    // Como UF é um dropdown, você precisa usar o change para ele mudar a view
    // Pelo que vi no código UF é seu id "default"
    $("#UF").val('UF').change();
}

Change success to:

success: function (data) {
    $("#endereco").html(data);
    limpaForm();
},
    
02.02.2015 / 15:09
4

You can add this to the callback success of your ajax request:

$('#Pessoa,#Cep,#Endereco,#Numero,#Complemento,#Bairro,#Cidade,#UF').val('');

An ideal solution would be to place these fields within a form . It facilitates both the time of sending and the time to clean the fields.

Ex:

<form id="form_endereco" action="" method="post">
    @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" })
    <br />
    @Html.Label("Complemento: ")
    @Html.TextBoxFor(e => e.Complemento, new { maxlength = "50", id = "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 />
</form>

And in its function adicionarEndereco() :

function adicionarEndereco() {
    // pega automaticamente todos os valores preenchidos no form 
    // sem a necessidade de declarar uma variável pra cada um
    var dados = $('#form_endereco').serialize();

    $.ajax(
        {
            type: "POST",
            url: "/Master/CadastrarEndereco",
            data: dados,
            success: function (data) {

                $("#endereco").html(data);

                // limpa todos os campos do form
                $('#form_endereco :input').val('');

            },
        });

        return false;
}
    
02.02.2015 / 15:19
2

Luiz Henrique's answer is nice, but whenever we can simplify something, you will become better.

You can do this in one line:

$('#meu-form').get(0).reset();

That way, if you add an extra input on your form, you will not have to add it to a function.

Where get(0) takes the element of DOM saved in Array generated by jQuery and reset is the native method of javascript to reset forms.

Note that reset returns the form to the initial state, it does not properly clean a form. If in the initial state an input has a value equal to 5, when reset it will return to have the value equal to 5.

You can do so in your success:

success: function (data) {

        $('#meu-form').get(0).reset();
    },
    
02.02.2015 / 15:15