pass data from jquery to the controller and return values

0

Would you like to know how I could do this?

My controller method is this:

public UserValid RetornaUsuario(String matricula)
{
    UserValid valid = new UserValid();
    UserValidDAO dao = new UserValidDAO();
    valid = dao.Busca(matricula);

    return valid;
}

I was trying to do something like this:

function PassarMatricula() {
    var parametros = {
        _matricula : $('#txtMatricula').val(),      
    };

    $.ajax({
        url : 'Home/RetornaUsuario',
        datatype : 'json',
        contentType : "application/json; charset=utf-8",
        type : "POST",
        data : JSON.stringify(parametros),
        success : function(data) {  

        },
        error : function(error) {
        }
    });    
}
    
asked by anonymous 03.02.2016 / 14:17

1 answer

1

As said in the comments by @Marconi, you can use Ajax to do this.

First you will send the data to your Action via Ajax, then do what you need and return the data via json to your view. An example would look like this:

Controller

        [HttpPost]
        public ActionResult BuscarCep(string cep)
        {
            var endereco = db.Endereco.FirstOrFefault(x => x.cep == cep);
            return Json(endereco, JsonRequestBehavior.AllowGet);
        }

View

<script>
        $('#txtCep').on('blur', function() {
            var cep= $('#txtCep').val();
            $.ajax({
                url: '@Url.Action("BuscarCep","Endereco")?cep=' + extensao,
                type: 'POST',
                success: function (data) {
                    //Preenche os inputs com os valores retornados aqui.
                    $('#txtEndereco').val(data.Endereco);
                }
            });
            return false;
        });
    </script>
    
03.02.2016 / 14:27