pass jquery data to the controller and return values

Asked

Viewed 1,502 times

0

I need that when textbox loses focus, pass the value you have in it to my controller, in my controller I will return an object to jquery, so I can fill in the other fields.

I wonder how I could do that?

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 this way:

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) {
        }
    });    
}
  • You can do it using Ajax. Return a Json and fill in. Post the html and Jquery you’ve been trying to use.

  • You only have this code?

1 answer

1

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

First you will send the data to your Action by Ajax, then do what you need and return the data via json for 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>
  • @Marconi I don’t know exactly what he needs. With ActionResult it can return whatever you want. json, partial view, etc.

  • Got it.Removing comments.

  • @Marconi could leave. To tell the truth this is a great question, in case you want to know the real reason of each type.

  • Vdd, ask the question there. rsrsrs

  • I will try to implement this way

Browser other questions tagged

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