JSON function Does not return value

Asked

Viewed 316 times

2

I have a problem, I would like to popular my Dropdownlistfor with the result of another Dropdownlistfor, for this I am using Ajax and Json, same concept they do when they want the result of State to City.

Model:

    public class SegmentMOD
        {
            public int id { get; set; }

            [DisplayName("Segmento")]
            public string nome { get; set; }
        }
            public class SectorMOD
        {
            public int id { get; set; }

            [DisplayName("Setor")]
            public string nome { get; set; }

            public int segmentId { get; set; }
        }

Controller:

    OpportunityController: Controller
    {

    public ActionResult Cadastrar()
            {
                //Aqui funciona normal, retorna os valores
                ViewBag.segmentList = new SelectList(new SegmentREP().ListarTodos(),
                    "id",
                    "nome"
                );

                return View();
            }
            //vai preencher o Where com o Id do segment
            public async Task<JsonResult> CarregarSector(int id)
        {
            var setor = new SectorREP().ListarTodos().Where(x => x.segmentId ==id);

            return Json(setor, JsonRequestBehavior.AllowGet);
        }

    }

View:

    @{
        ViewBag.Title = "Cadastrar";
    }

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js">
</script>
<script>
    $(document).ready(function () {
        $("#segment").change(function () {
            listaCidade($(this).val());
        });
    });

    //chamada ajax para a Action ListaCidade
    //passando como parâmetro a Estado selecionado
    function listaCidade(segmentId) {
        //Chamando o metodo do controller para retornar um JSON
        $.ajax({
            url: '/Opportunity/CarregarSector',
            type: 'POST',
            data: { id: segmentId },
            dataType: 'json',
            success: function (result) {
                $("#sector").empty();
                $(result).each(function () {
                    //adicionando as opções de acordo com o retorno
                    $("#sector").append("<option value='" + this.id + "'>" + this.nome + "</option>");
                });
            },
            error: function () {
                alert('Erro! Não foi possível carregar os Setores.');
            }
        });

    }
</script>



        <h2>Cadastrar</h2>


                                                <div class="col-md-4">
        @Html.LabelFor(model => model.segment, htmlAttributes: new { @class = "control-label" })

        @Html.DropDownListFor(model => model.segment, (SelectList)ViewBag.segmentList, new { @class = "form-control selectpicker show-tick", data_live_search = "true", id = "segment" })
        @Html.ValidationMessageFor(model => model.segment, "", new { @class = "text-danger" })

                            <select class="form-control" id="sector"></select>

                        </div>
  • 2

    You have already tested Ajax by calling it manually?

  • How would that be ?

  • I’ll try to use the tool more if you have the solution thank you.

  • So, but I need to know more things in order to be able to answer you. Ajax agreeing is one of them. Then I will look at the rest you put. Just with that I can’t tell you what it is.

  • I’m testing more unsuccessfully I need another alternative, but I’ll try in that time.

  • Do the following: make JSON return output using GET, not POST. As it is read only what you are doing, avoid putting unnecessary complications.

  • It brings a result like this. Load sector? id=2; I would like to know the result of (result), plus it of the error and executes the error: Function()

  • Good, then it gives error even. The JS console returns something? The code in ASP.NET gives error?

  • The Asp.net code does not return an error and the JS console only (id=2) does not return anything either.

  • [Httppost] public Jsonresult Loadable (int id) { Return Json (new Sectorrep().Listings().Where(x => x.segmentId == id); } that return ID(id=2) and to complete my Where, and the result would be that Return(Return Json)above, will this format I am returning this correct ?

  • I told you to take the test without the [Httppost]. Why it hasn’t been done yet?

  • I Fez, I didn’t know the difference.

  • Friends, I am in need of help because I don’t have a solution... Thank you all and thank you very much to Gypsy Morrison, for the help so far.

  • Gypsy, I managed to print the value on the Json screen by passing the ID, in the url in the same hand, now I wanted to take and pass the Dropdownlist ID and pass as parameter of the method to list the sectors, the sucess: of the ajax that error.

  • You can edit your question and put how the code is until then?

  • Thank you, I managed to solve the problem.

Show 12 more comments

2 answers

2


Model:

        public class SegmentMOD
            {
                public int id { get; set; }

                [DisplayName("Segmento")]
                public string nome { get; set; }
            }
                public class SectorMOD
            {
                public int id { get; set; }

                [DisplayName("Setor")]
                public string nome { get; set; }

                public int segmentId { get; set; }
            }

    Controller:

        OpportunityController: Controller
        {

        public ActionResult Cadastrar()
                {
                    //Aqui funciona normal, retorna os valores
                    ViewBag.segmentList = new SelectList(new SegmentREP().ListarTodos(),
                        "id",
                        "nome"
                    );

                    return View();
                }
                //vai preencher o Where com o Id do segment
                public async Task<JsonResult> CarregarSector(int id)
            {
                var setor = new SectorREP().ListarTodos().Where(x => x.segmentId ==id);

                return Json(setor, JsonRequestBehavior.AllowGet);
            }

        }

    View:

        @{
            ViewBag.Title = "Cadastrar";
        }

            <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#segment").change(function () {
                listaSector($(this).val());
            });
        });

        //chamada ajax para a Action CarregarSector
        //passando como parâmetro o Segmento selecionado
        function listaSector(segmentId) {
            //Chamando o metodo do controller para retornar um JSON
            $.ajax({
                url: '/Opportunity/CarregarSector',
                type: 'POST',
                data: { id: segmentId },
                dataType: 'json',
                success: function (result) {
                    $("#sector").empty();
                    $(result).each(function () {
                        //adicionando as opções de acordo com o retorno
                        $("#sector").append("<option value='" + this.id + "'>" + this.nome + "</option>");
                    });
                },
                error: function () {
                    alert('Erro! Não foi possível carregar os Setores.');
                }
            });

        }
    </script>



            <h2>Cadastrar</h2>


                                                    <div class="col-md-4">
            @Html.LabelFor(model => model.segment, htmlAttributes: new { @class = "control-label" })

            @Html.DropDownListFor(model => model.segment, (SelectList)ViewBag.segmentList, new { @class = "form-control selectpicker show-tick", data_live_search = "true", id = "segment" })
            @Html.ValidationMessageFor(model => model.segment, "", new { @class = "text-danger" })

                                <select class="form-control" id="sector"></select>

                            </div>

0

A solution would be to generate html code directly in the controller.

 //Gera options do selectlist
  StringBuilder strHtml = new StringBuilder();
  strHtml.Append("<option value='0'>Selecione...</option>");
  foreach ( var sector in sectorList )
  {
       //Para cada resultado encontrado gera uma option para o selectlist
       strHtml.AppendFormat("<option value='{0}'>{1}</option>", sector.id, sector.nome);
  }
       //retorna html referente ao selectlist sector
       return Json(new { options = strHtml.ToString() });

And on the return of the ajax function give the append of the options in the respective select.

 success: function (result) {
            $("#sector").empty();
            $("#sector").html(result.options);
        },

Browser other questions tagged

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