ASP.Net fill a DropDownList depending on another using Ajax and Rest service

2

I hope you can help me with this problem. What I want to achieve is fill a dropDownList depending on the selection of another that I load in the page_load, I'm using a rest service to do the data loading and C # language.

The first DropDownList charges it this way in the Page_Load

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            var url = "http://localhost:8090/Galenos/webresources/especialidadController/getData";
            var webRest = new WebClient();
            var content = webRest.DownloadString(url);


            DataContractJsonSerializer dj = new DataContractJsonSerializer(typeof(Especialidad[]));
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
            {
                //var p = (prevision)dj.ReadObject(ms);
                Especialidad[] p = (Especialidad[])dj.ReadObject(ms);

                foreach (Especialidad x in p)
                {
                    ListItem pv = new ListItem(x.nombre, x.id.ToString());
                    especialidades.Items.Add(pv);
                }
            }
        }
        catch (SerializationException ex)
        {


        }
        catch (Exception ex)
        {

        }
    }

Look for something online and to fill the second DropDownList use this JavaScript code

$(document).ready(function () {
$("#especialidades").change(function () {

    alert("change");
    $.ajax({
        type: "GET",
        url: "http://localhost:8090/Galenos/webresources/usuarioController/getMedico",
        data: "{esp: '" + $('#especialidades').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
             alert("entra");
            var models = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            $("#medicos").get(0).options.length = 0;

            for (var i = 0; i < models.length; i++) {
                var val = models[i].rut;
                var text = models[i].nombre;
                $("#medicos").get(0).options[$("#medicos").get(0).options.length] = new Option(text, val);

            }
        },
        error: function (response) {
            if (response.length != 0)
                alert("error"+response);
        }
    });
});

});

But it does not work, does not load the second DropDownList, the url of the rest service if it works, because when I put in the browser the json returns me with the data of the doctors

The asp code of the DropDownList declaration is this

<label for="especialidades">Especialidad medica :</label>
        <asp:DropDownList ID="especialidades" ClientIDMode=Static  runat="server"></asp:DropDownList>
    <br/>
    <label for="medicos">Medico :</label>
        <asp:DropDownList ID="medicos" ClientIDMode=Static  runat="server"></asp:DropDownList>
    <br />

If there is another way to make this data load it would be fine for my equal, it does not necessarily have to be with Ajax, it's just that I read that the best way would be like this, but I do not know how this works very well

    
asked by Mirko Hernandez 25.05.2017 в 03:56
source

2 answers

0

Try this part of the code and it works, then the problem is that the change event of the first DropdownList is not firing or that it is not recovering the data. This you can test very easily.

Greetings,

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

<script>
    var response = {
        d: [
            {
                rut: '12',
                nombre: 'Jorge'
            }
        ]

    };

    alert("entra");
    var models = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
    $("#medicos").get(0).options.length = 0;

    for (var i = 0; i < models.length; i++) {
        var val = models[i].rut;
        var text = models[i].nombre;
        $("#medicos").get(0).options[$("#medicos").get(0).options.length] = new Option(text, val);

    }
</script>
    
answered by 25.05.2017 в 04:20
0

In the end what I found was to pass the variable to the url

 url: "http://localhost:8090/Galenos/webresources/usuarioController/getMedico/" + $('#especialidades').val(),

I deleted the line

data: "{esp: '" + $('#especialidades').val() + "'}",

and use a chrome without security or something like that ... I did not understand that correctly, it's called CORS, I followed the instructions here link

I do not know if it's the best solution but it worked for me

    
answered by 25.05.2017 в 08:44