locked
How to get data from webmethod im select option using jquery RRS feed

  • Question

  • User932259438 posted

    hello,

    my code not works. I have tried with $.each as you can see , but not works.

    Maybe is problem in webmethod.

    1. WebMethod

      [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string voznik(string username, string password, int IdPodjetja)
        {
            if (Membership.ValidateUser(username, password) && IdPodjetja != null)
            {
                //voznik
                var voznik = from c in db.tbl_zaposlenis
                             where c.Idkreiranopodjetje == IdPodjetja
                             orderby c.Priimek
                             select new
                             {
                                 Value = c.ID,
                                 Text = c.Priimek + " " + c.Ime
    
                             };
    
                prikazivoznika = new JavaScriptSerializer().Serialize(voznik.ToList());
    
            }
            return prikazivoznika;
        }

    2. Webmethod

        [WebMethod]
        public string List<ListItem> voznik(string username, string password, int IdPodjetja)
    
            //string username, string password, int IdPodjetja)
        {
          //  List<ListItem> customers = new List<ListItem>();
          //  if (Membership.ValidateUser(username, password) && IdPodjetja != null)
          //  {
                string query = "SELECT ID, Priimek, Ime FROM tbl_zaposlenis WHERE Idkreiranopodjetje=1370";
                string constr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        List<ListItem> customers = new List<ListItem>();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            while (sdr.Read())
                            {
                                customers.Add(new ListItem
                                {
                                    Value = sdr["Priimek"].ToString(),   //+ " "+ sdr["Ime"].ToString(),
                                    Text = sdr["ID"].ToString()
                                });
                            }
                        }
                        con.Close();
                        return customers;
                    }
                }
          //  }
            

    ajax:

     $(function () {
        $.ajax({
            type: "POST",
            url: "/hanja.asmx/voznik",
            data: JSON.stringify({ username: $.cookie("user"), password: $.cookie("pass"), IdPodjetja: localStorage.getItem("IdPodjetja") }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var ddlCustomers = $("[id*=ddlVozniki]");
                ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>')
    
                $.each(response, function(i, item) {
                alert(item.ID);
            });
    
                //////$.each(r, function () {
                //////    alert("OK");
                ////////    ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
                //////});
    
                ////$.each(r.d, function () {
    
                ////    alert(r);
    
                ////    ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
                ////});
            }
        });
    });
        <select id="ddlVozniki">
        </select>

    I have tried to use the same example from https://www.aspsnippets.com/Articles/Populate-Bind-ASPNet-DropDownList-using-jQuery-AJAX-and-JSON-in-C-and-VBNet.aspx


    Response is 200, everything is ok, but in Select option not display data.

    Please help.

    Saturday, January 18, 2020 9:34 PM

Answers

  • User281315223 posted

    By default, WebMethods will return the data in a 'd' property, so you'll need to access that and iterate over the values:

    $(function () {
        $.ajax({
            // Omitted for brevity
            success: function (response) {
                var ddlCustomers = $("[id*=ddlVozniki]");
                ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>')
    
                // Read each item in the 'd' property
                $.each(response.d, function(i, item) {
                    // Append it to your list
                    ddlCustomers.append(`<option value='{item.ID}'>{item.Priimek}</option>`);
                });
            }
            // Omitted for brevity
        });
    });

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 19, 2020 1:50 AM
  • User288213138 posted

    Hi progy85,

    public string List<ListItem> voznik(string username, string password, int IdPodjetja)

    Webmethod can only have one type and needs to be set to static. and if you want to iterate over the returned values, you should use response.d.

    My tested code:

    <script>
            $(function () {
                $.ajax({
                    type: "POST",
                    url: "WebForm4.aspx/voznik",
                    data: JSON.stringify({ username: "user", password: "pass", IdPodjetja: 1 }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var ddlCustomers = $("[id*=ddlVozniki]");
                        ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>')
                        $.each(response.d, function (i, item) {
                            alert(item.ID);
                        });
                    }
                });
            });
        </script>
    
    [WebMethod]
    
            public static List<ListItem> voznik(string username, string password, int IdPodjetja)
            {
    
                string query = "SELECT ID, Priimek, Ime FROM tbl_zaposlenis WHERE Idkreiranopodjetje=1370";
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        List<ListItem> customers = new List<ListItem>();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            while (sdr.Read())
                            {
                                customers.Add(new ListItem
                                {
                                    Value = sdr["Priimek"].ToString(),
                                    Text = sdr["ID"].ToString()
                                });
                            }
                        }
                        con.Close();
                        return customers;
                    }
                }
            }

    The result:

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 19, 2020 3:30 AM

All replies

  • User281315223 posted

    By default, WebMethods will return the data in a 'd' property, so you'll need to access that and iterate over the values:

    $(function () {
        $.ajax({
            // Omitted for brevity
            success: function (response) {
                var ddlCustomers = $("[id*=ddlVozniki]");
                ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>')
    
                // Read each item in the 'd' property
                $.each(response.d, function(i, item) {
                    // Append it to your list
                    ddlCustomers.append(`<option value='{item.ID}'>{item.Priimek}</option>`);
                });
            }
            // Omitted for brevity
        });
    });

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 19, 2020 1:50 AM
  • User288213138 posted

    Hi progy85,

    public string List<ListItem> voznik(string username, string password, int IdPodjetja)

    Webmethod can only have one type and needs to be set to static. and if you want to iterate over the returned values, you should use response.d.

    My tested code:

    <script>
            $(function () {
                $.ajax({
                    type: "POST",
                    url: "WebForm4.aspx/voznik",
                    data: JSON.stringify({ username: "user", password: "pass", IdPodjetja: 1 }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var ddlCustomers = $("[id*=ddlVozniki]");
                        ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>')
                        $.each(response.d, function (i, item) {
                            alert(item.ID);
                        });
                    }
                });
            });
        </script>
    
    [WebMethod]
    
            public static List<ListItem> voznik(string username, string password, int IdPodjetja)
            {
    
                string query = "SELECT ID, Priimek, Ime FROM tbl_zaposlenis WHERE Idkreiranopodjetje=1370";
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        List<ListItem> customers = new List<ListItem>();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            while (sdr.Read())
                            {
                                customers.Add(new ListItem
                                {
                                    Value = sdr["Priimek"].ToString(),
                                    Text = sdr["ID"].ToString()
                                });
                            }
                        }
                        con.Close();
                        return customers;
                    }
                }
            }

    The result:

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 19, 2020 3:30 AM