Load input text after selecting select

0

I have a select that is being populated via ajax, when I open the modal, I call the function that loads the select, and it is working perfectly.

But I need a cascade type effect in the first field, and when changing, it changes the input text according to the field selected. How can I do it? I'm trying to do this:

function Carrega(id) {
    $.ajax({
        type: "post",
        url: "/PessoasServicos/CarregaDados",
        data: { id },
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            var tipoplano = $('#txtTipoPlano');
            tipoplano = data.resultado;
        }
    });
}

$('#cbplanos').on("click", function () {
    Carrega(1);
});

I'm passing the direct id 1, to do a test, and here is the controller:

  [HttpPost]
    public ActionResult CarregaDados(int id)
    {
        try
        {
            var resultado = (from a in _context.PlanosServicos
                          where a.Id == id
                          select new
                          {
                              a.Tipo,
                          });

            return Json(resultado);
        }
        catch (Exception ex)
        {
            return Json(new { Result = ex.Message });
        }
    }

But it does not return an error, but it does not return what I need.

    
asked by anonymous 29.06.2018 / 14:53

1 answer

1

I edited the Carrega method by passing id to data and set return within input

function Carrega(id) {
    $.ajax({
        type: "post",
        url: "/PessoasServicos/CarregaDados",
        data: { id: id },
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $("#txtTipoPlano").val(data.tipo)
        }
    });
}

Try to call the event directly on select , it would look like this:

<select id="cbplanos" onchange="Carrega(this.value)"></select>

Finally, since you are selecting only one item, I have thrown this value for a variable and then yes I returned a new json with the field tipo

public ActionResult CarregaDados(int id)
{
    try
    {
        var resultado = _context.PlanosServicos.Where(p=> p.Id == id).FirstOrDefault().Tipo;

        return Json(new { tipo = resultado});
    }
    catch (Exception ex)
    {
        return Json(new { Result = ex.Message });
    }
}
    
29.06.2018 / 16:06