locked
Filter Data Based Without Postback using jquery RRS feed

  • Question

  • User-807418713 posted

    Hello

    I have Two Dropdownlist And One Textbox In My Page 

    Dropdownlist1 has to bind Supplier

    Dropdownlist2 has to bind ItemName Based On Selected Supplier

    Textbox1 has to bind based on Supplier Name + ItemName selected Value 

    For this below is sql data table with data

     
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    SET ANSI_PADDING ON
    GO
    CREATE TABLE [dbo].[Personal_Details](
    	[ID] [int] IDENTITY(1,1) NOT NULL,
    	[Supplier] [varchar](50) NULL,
    	[ItemName] [varchar](50) NULL,
    	[Rate] [float] NULL,
     CONSTRAINT [PK_Personal_Details] PRIMARY KEY CLUSTERED 
    (
    	[ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    SET ANSI_PADDING OFF
    GO
    SET IDENTITY_INSERT [dbo].[Personal_Details] ON
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (1, N'ABCD', N'Item1', 10)
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (2, N'ABCD', N'Item2', 12)
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (3, N'ABCD', N'Item3', 16)
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (4, N'ABCD', N'Item4', 22)
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (5, N'KLMN', N'Item11', 2)
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (6, N'KLMN', N'Item12', 6)
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (7, N'VWXY', N'Item23', 9)
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (8, N'VWXY', N'Item24', 6)
    INSERT [dbo].[Personal_Details] ([ID], [Supplier], [ItemName], [Rate]) VALUES (9, N'VWXY', N'Item25', 77)
    SET IDENTITY_INSERT [dbo].[Personal_Details] OFF
    

    From The Above Code For Example VWXY Then it should show in dropdownlist2 :

     Item23 

    Item24 

    Item25

    now i select Item24 Now in textbox it has to show 6

    How to achieve this without postback in asp.net 2.0 C# Jquery

    Thank You

    Sunday, June 9, 2019 10:36 AM

Answers

  • User475983607 posted

    There are several confusing design issues.  The Web Methods return a string but the AJAX function is expecting JSON.  The Item and supplier are on the same record so I don't get the need to fill two selects from the same table.

    I recommend using strong types rather than DataSets and letting the framework handling the serialization.  Below is a tested example.

    Model

        public class PersonalDetails
        {
            private int _id;
            private string _supplier;
            private string _itemName;
            private double _rate;
    
            public int ID
            {
                get { return _id; }
                set { _id = value;  }
            }
    
            public string Supplier
            {
                get { return _supplier; }
                set { _supplier = value; }
            }
    
            public string ItemName
            {
                get { return _itemName; }
                set { _itemName = value; }
            }
    
            public double Rate
            {
                get { return _rate; }
                set { _rate = value; }
            }
    
        }

    Markup

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebFormsDemo._default" %>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link href="content/bootstrap.css" rel="stylesheet" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                SetDrop1();//bind dropdownlist1
                $("#DropDownList1").change(function () {
                    var selectedText = $(this).find(':selected').text();
                    SetDrop2(selectedText);
                });
                $("#DropDownList2").change(function () {
                    $("#TextBox1").val($("#DropDownList2").val());
                });
            })
            function SetDrop1() {
                $("#<%=DropDownList1.ClientID%>").empty();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/DropDownList1Bind",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = result.d;
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#<%=DropDownList1.ClientID%>").append("<option value='" + response[i]['ID'] + "'>" + response[i]['Supplier'] + "</option>");
                        }
                        SetDrop2($('#<%=DropDownList1.ClientID%> :selected').text());
                    }
                });
            }
    
            function SetDrop2(selectedText) {
                $("#<%=DropDownList2.ClientID%>").empty();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/DropDownList1Change",
                    data: '{supplier: "' + selectedText + '" }',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = result.d;
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#<%=DropDownList2.ClientID%>").append("<option value='" + response[i]['Rate'] + "'>" + response[i]['ItemName'] + "</option>");
                        }
                        $("#<%=TextBox1.ClientID %>").val($("#<%=DropDownList2.ClientID%>").val());
                    },
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
           </div>
           <div>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </div>
        </form>
    </body>
    </html>
    
    
    
    

    Code behind

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using WebFormsDemo.Models;
    
    namespace WebFormsDemo
    {
        public partial class _default : System.Web.UI.Page
        {
    
            protected void Page_Load(object sender, EventArgs e)
            {
                
    
            }
    
            [WebMethod]
            public static List<PersonalDetails>  DropDownList1Bind()
            {
                List<PersonalDetails> details = new List<PersonalDetails>();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM dbo.Personal_Details;", conn);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        PersonalDetails detail = new PersonalDetails();
                        detail.ID = (int)reader["ID"];
                        detail.Supplier = (string)reader["Supplier"];
                        detail.ItemName = (string)reader["ItemName"];
                        detail.Rate = (double)reader["Rate"];
                        details.Add(detail);
                    }
                    reader.Close();
                }
                conn.Close();
                return details;
            }
            [WebMethod]
            public static List<PersonalDetails> DropDownList1Change(string supplier)
            {
                List<PersonalDetails> details = new List<PersonalDetails>();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM dbo.Personal_Details WHERE Supplier = @Supplier;", conn);
                command.Parameters.AddWithValue("@Supplier", supplier);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        PersonalDetails detail = new PersonalDetails();
                        detail.ID = (int)reader["ID"];
                        detail.Supplier = (string)reader["Supplier"];
                        detail.ItemName = (string)reader["ItemName"];
                        detail.Rate = (double)reader["Rate"];
                        details.Add(detail);
                    }
                    reader.Close();
                }
                conn.Close();
                return details;
            }
    
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 11, 2019 2:10 PM
  • User665608656 posted

    Hi Gop.MCA,

    I suggest that you try to return a JSON string to the foreground in the webmethod, and then use JSON.parse in JS to convert the JSON string into object.

    Here are detailed code:

    <!DOCTYPE html>
    
    <html>
    <head runat="server">
        <title>Untitled Page</title>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                SetDrop1();//bind dropdownlist1
                $("#DropDownList1").change(function () {
                    var selectedText = $(this).find(':selected').text();
                    SetDrop2(selectedText);
                });
                $("#DropDownList2").change(function () {
                    $("#TextBox1").val($("#DropDownList2").val());
                });
            })
            function SetDrop1() {
                $("#DropDownList1").empty();
                $.ajax({
                    type: "POST",
                    url: "WebForm_0613_2156419.aspx/DropDownList1Bind",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = JSON.parse(result.d);
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#DropDownList1").append("<option value='" + response[i]['ID'] + "'>" + response[i]['Supplier'] + "</option>");
                        }
                        SetDrop2($('#DropDownList1 :selected').text());
                    }
                });
            }
    
            function SetDrop2(selectedText) {
                $("#DropDownList2").empty();
                $.ajax({
                    type: "POST",
                    url: "WebForm_0613_2156419.aspx/DropDownList1Change",
                    data: '{supplier: "' + selectedText + '" }',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = JSON.parse(result.d);
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#DropDownList2").append("<option value='" + response[i]['Rate'] + "'>" + response[i]['ItemName'] + "</option>");
                        }
                        $("#TextBox1").val($("#DropDownList2").val());
                    },
                });
            }
        </script>
    
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
    
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    
            </div>
        </form>
    </body>
    </html>
    

    code behind:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1.Cases
    {
        public partial class WebForm_0613_2156419 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            public class PersonalDetails
            {
                private int _id;
                private string _supplier;
                private string _itemName;
                private double _rate;
    
                public int ID
                {
                    get { return _id; }
                    set { _id = value; }
                }
    
                public string Supplier
                {
                    get { return _supplier; }
                    set { _supplier = value; }
                }
    
                public string ItemName
                {
                    get { return _itemName; }
                    set { _itemName = value; }
                }
    
                public double Rate
                {
                    get { return _rate; }
                    set { _rate = value; }
                }
    
            }
    
    
            [WebMethod]
            public static string DropDownList1Bind()
            {
                List<PersonalDetails> details = new List<PersonalDetails>();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM Personal_Details;", conn);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        PersonalDetails detail = new PersonalDetails();
                        detail.ID = (int)reader["ID"];
                        detail.Supplier = (string)reader["Supplier"];
                        detail.ItemName = (string)reader["ItemName"];
                        detail.Rate = (double)reader["Rate"];
                        details.Add(detail);
                    }
                    reader.Close();
                }
                conn.Close();
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string myJson = jss.Serialize(details);
                return myJson;
            }
    
    
            [WebMethod]
            public static string DropDownList1Change(string supplier)
            {
                List<PersonalDetails> details = new List<PersonalDetails>();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM dbo.Personal_Details WHERE Supplier = @Supplier", conn);
                command.Parameters.AddWithValue("@Supplier", supplier);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        PersonalDetails detail = new PersonalDetails();
                        detail.ID = (int)reader["ID"];
                        detail.Supplier = (string)reader["Supplier"];
                        detail.ItemName = (string)reader["ItemName"];
                        detail.Rate = (double)reader["Rate"];
                        details.Add(detail);
                    }
                    reader.Close();
                }
                conn.Close();
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string myJson = jss.Serialize(details);
                return myJson;
            }
    
        }
    }

    If this method still does not solve your issue, please use F12 to show me the value of result.d?

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 13, 2019 9:10 AM

All replies

  • User665608656 posted

    Hi Gopi.MCA,

    According to your description, to implement this function in asp.net 2.0 by using jquery, I recommend you use webmethod.

    First, when the page is loaded, bind the data source of DropDownList1 by webmethod in jquery.

    After the binding is completed, the value of the current default supplier selected by DropDownList1 is obtained which as a parameter to continue to bind the ItemName data source of DropDownList2.

    After the binding is completed, in the same way, they get the current selected value of DropDownList2, and use webmethod to get the corresponding Rate value in the code behind and bind it to textbox.

    When DropDownList1 or DropDownList2 chooses to change, use jQuery to trigger the change event and continue to use webmethod to rebind the value in the corresponding event.

    For more details, you could refer to the following code:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="../Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
            $(function () {
                SetDrop1();//bind dropdownlist1
    $("#DropDownList1").change(function () { var selectedText = $(this).find(':selected').text(); SetDrop2(selectedText); }); $("#DropDownList2").change(function () { var selectedVal = $(this).find(':selected').val(); SetTextBox(selectedVal); }); })
    function SetDrop1() { $.ajax({ type: "POST", url: "WebForm_0610_2156419.aspx/DropDownList1Bind", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { $("#DropDownList1").empty(); $(result.d).find("drop1").each(function () { // Get the OptionValue and OptionText Column values. var OptionValue = $(this).find('ID').text(); var OptionText = $(this).find('Supplier').text(); // Create an Option for DropDownList. var option = $("<option>" + OptionText + "</option>"); option.attr("value", OptionValue); $("#DropDownList1").append(option); }); var loadText = $('#DropDownList1 :selected').text(); SetDrop2(loadText);//bind dropdownlist2 and bind textbox }, }); } function SetDrop2(selectedText) { $.ajax({ type: "POST", url: "WebForm_0610_2156419.aspx/DropDownList1Change", data: '{supplier: "' + selectedText + '" }', contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { $("#DropDownList2").empty(); $(result.d).find("drop2").each(function () { // Get the OptionValue and OptionText Column values. var OptionValue = $(this).find('ID').text(); var OptionText = $(this).find('ItemName').text(); // Create an Option for DropDownList. var option = $("<option>" + OptionText + "</option>"); option.attr("value", OptionValue); $("#DropDownList2").append(option); }); SetTextBox($("#DropDownList2").val()); }, }); } function SetTextBox(selectedVal) { $.ajax({ type: "POST", url: "WebForm_0610_2156419.aspx/DropDownList2Change", data: '{ID: "' + selectedVal + '" }', contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { $("#TextBox1").val(result.d); }, }); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList> &nbsp; &nbsp; <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList> <br /> <br /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </div> </form> </body> </html>

    code behind:

    protected void Page_Load(object sender, EventArgs e)
            {
            }
            [WebMethod]
            public static string DropDownList1Bind()
            {
                DataTable dt = BindData1();
                dt.TableName = "drop1";
                // Convert the DataTable to XML.
                string result;
                using (StringWriter sw = new StringWriter())
                {
                    dt.WriteXml(sw);
                    result = sw.ToString();
                }
                return result;
            }
            [WebMethod]
            public static string DropDownList1Change(string supplier)
            {
                DataTable dt = BindData2(supplier);
                dt.TableName = "drop2";
                // Convert the DataTable to XML.
                string result;
                using (StringWriter sw = new StringWriter())
                {
                    dt.WriteXml(sw);
                    result = sw.ToString();
                }
                return result;
            }
            [WebMethod]
            public static string DropDownList2Change(string ID)
            {
                string rate = BindData3(ID);
                return rate;
            }
            protected static DataTable BindData1()
            {
                DataTable dt = new DataTable();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("select * from  Personal_Details ", conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dt = ds.Tables[0];
                conn.Close();
                return dt;
            }
            protected static DataTable BindData2(string supplier)
            {
                DataTable dt = new DataTable();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("select * from  Personal_Details where  Supplier= @Supplier", conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                cmd.Parameters.AddWithValue("@Supplier", supplier);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dt = ds.Tables[0];
                conn.Close();
                return dt;
            }
            public static string BindData3(string id)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("select Rate from  Personal_Details where  ID= @ID", conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                cmd.Parameters.AddWithValue("@ID", id);
                DataSet ds = new DataSet();
                da.Fill(ds);
                conn.Close();
                return ds.Tables[0].Rows[0][0].ToString();
            }

    The result of my work demo:

    Best Regards,

    YongQing.

    Monday, June 10, 2019 5:24 AM
  • User-807418713 posted

    Hi

    On Page Load i got this error

    {Message: "There is no row at position 0.",…}
    ExceptionType: "System.IndexOutOfRangeException"
    Message: "There is no row at position 0."
    StackTrace: "   at System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex)
    ↵   at System.Data.RBTree`1.get_Item(Int32 index)
    ↵   at System.Data.DataRowCollection.get_Item(Int32 index)
    ↵   at _Default.BindData3(String id)
    ↵   at _Default.DropDownList2Change(String ID)"

    Note: Table ID Column is Int auto increment field

    Monday, June 10, 2019 6:45 PM
  • User-807418713 posted

    Hello

    Is That Any thing possible with short query it very long i mean on simple page load we can call this select Supplier, ItemName, Rate from Personal_Details 

    From this page load query any simple and easy code to filter data

    Something like for example below

    <script>
            $(function () {
                $(".mytext").val($(".myddl").val())
                $(".myddl").change(function () {
                    $(".mytext").val($(this).val())
    
                })
    
    
            })
        </script> 

    Thanks

    Monday, June 10, 2019 6:58 PM
  • User665608656 posted

    Hi Gopi.MCA,

    According to your description, maybe you could simplify the method of binding textbox.

    However, to bind data sources to dropdownlist1 and dropdownlist2, you still need to use the webmethod in jQuery to call the code behind, so as to ensure that when you select different items, the page will not be post back.

    You could modify the code as follows, which should also solve your last issue.

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="../Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
            $(function () {
                SetDrop1();//bind dropdownlist1
                $("#DropDownList1").change(function () {
                    var selectedText = $(this).find(':selected').text();
                    SetDrop2(selectedText);
                });
                $("#DropDownList2").change(function () { 
                     $("#TextBox1").val($("#DropDownList2").val()); 
                });
            })
            function SetDrop1() {
                $.ajax({
                    type: "POST",
                    url: "WebForm_0610_2156419.aspx/DropDownList1Bind",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        $("#DropDownList1").empty();
                        $(result.d).find("drop1").each(function () {
                            // Get the OptionValue and OptionText Column values.
                            var OptionValue = $(this).find('ID').text();
                            var OptionText = $(this).find('Supplier').text();
                            // Create an Option for DropDownList.
                            var option = $("<option>" + OptionText + "</option>");
                            option.attr("value", OptionValue);
                            $("#DropDownList1").append(option);
                        });
                        var loadText = $('#DropDownList1 :selected').text();
                        SetDrop2(loadText);//bind dropdownlist2 and bind textbox
                    },
                });
            }
    
            function SetDrop2(selectedText) {
                $.ajax({
                    type: "POST",
                    url: "WebForm_0610_2156419.aspx/DropDownList1Change",
                    data: '{supplier: "' + selectedText + '" }',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        $("#DropDownList2").empty();
                        $(result.d).find("drop2").each(function () {
                            // Get the OptionValue and OptionText Column values.
                            var OptionValue = $(this).find('Rate').text();
                            var OptionText = $(this).find('ItemName').text();
                            // Create an Option for DropDownList.
                            var option = $("<option>" + OptionText + "</option>");
                            option.attr("value", OptionValue);
                            $("#DropDownList2").append(option);
                        });
                          $("#TextBox1").val($("#DropDownList2").val());
                    },
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                &nbsp; &nbsp;
                <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
                <br />
                <br />
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </div>
    
        </form>
    </body>
    </html>
    

    code behind:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1.Cases
    {
        public partial class WebForm_0610_2156419 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
            }
    [WebMethod] public static string DropDownList1Bind() { DataTable dt = BindData1(); dt.TableName = "drop1"; // Convert the DataTable to XML. string result; using (StringWriter sw = new StringWriter()) { dt.WriteXml(sw); result = sw.ToString(); } return result; } [WebMethod] public static string DropDownList1Change(string supplier) { DataTable dt = BindData2(supplier); dt.TableName = "drop2"; // Convert the DataTable to XML. string result; using (StringWriter sw = new StringWriter()) { dt.WriteXml(sw); result = sw.ToString(); } return result; } protected static DataTable BindData1() { DataTable dt = new DataTable(); SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("select * from Personal_Details ", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); dt = ds.Tables[0]; conn.Close(); return dt; } protected static DataTable BindData2(string supplier) { DataTable dt = new DataTable(); SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("select * from Personal_Details where Supplier= @Supplier", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); cmd.Parameters.AddWithValue("@Supplier", supplier); DataSet ds = new DataSet(); da.Fill(ds); dt = ds.Tables[0]; conn.Close(); return dt; } } }

    Best Regards,

    YongQing.

    Tuesday, June 11, 2019 12:52 AM
  • User-807418713 posted

    Hello Yongqing Yu

    Thanks For Your Code 

    Below Is My Complete Page but not working my side why

    aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
        <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
     <script type="text/javascript">
            $(function () {
                SetDrop1();//bind dropdownlist1
                $("#DropDownList1").change(function () {
                    var selectedText = $(this).find(':selected').text();
                    SetDrop2(selectedText);
                });
                $("#DropDownList2").change(function () { 
                     $("#TextBox1").val($("#DropDownList2").val()); 
                });
            })
            function SetDrop1() {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/DropDownList1Bind",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        $("#DropDownList1").empty();
                        $(result.d).find("drop1").each(function () {
                            // Get the OptionValue and OptionText Column values.
                            var OptionValue = $(this).find('ID').text();
                            var OptionText = $(this).find('Supplier').text();
                            // Create an Option for DropDownList.
                            var option = $("<option>" + OptionText + "</option>");
                            option.attr("value", OptionValue);
                            $("#DropDownList1").append(option);
                        });
                        var loadText = $('#DropDownList1 :selected').text();
                        SetDrop2(loadText);//bind dropdownlist2 and bind textbox
                    },
                });
            }
    
            function SetDrop2(selectedText) {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/DropDownList1Change",
                    data: '{supplier: "' + selectedText + '" }',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        $("#DropDownList2").empty();
                        $(result.d).find("drop2").each(function () {
                            // Get the OptionValue and OptionText Column values.
                            var OptionValue = $(this).find('Rate').text();
                            var OptionText = $(this).find('ItemName').text();
                            // Create an Option for DropDownList.
                            var option = $("<option>" + OptionText + "</option>");
                            option.attr("value", OptionValue);
                            $("#DropDownList2").append(option);
                        });
                          $("#TextBox1").val($("#DropDownList2").val());
                    },
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                &nbsp; &nbsp;
                <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
                <br />
                <br />
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <br />
            <br />
            </div>
        </form>
    </body>
    </html>
    

    aspx.cs

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.Web.Services;
    using System.Configuration;
    using System.IO;
    using System.Text;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
             
        }
    
       [WebMethod]
            public static string DropDownList1Bind()
            {
                DataTable dt = BindData1();
                dt.TableName = "drop1";
                // Convert the DataTable to XML.
                string result;
                using (StringWriter sw = new StringWriter())
                {
                    dt.WriteXml(sw);
                    result = sw.ToString();
                }
                return result;
            }
            [WebMethod]
            public static string DropDownList1Change(string supplier)
            {
                DataTable dt = BindData2(supplier);
                dt.TableName = "drop2";
                // Convert the DataTable to XML.
                string result;
                using (StringWriter sw = new StringWriter())
                {
                    dt.WriteXml(sw);
                    result = sw.ToString();
                }
                return result;
            }
           
            protected static DataTable BindData1()
            {
                DataTable dt = new DataTable();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("select * from Personal_Details", conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dt = ds.Tables[0];
                conn.Close();
                return dt;
            }
            protected static DataTable BindData2(string supplier)
            {
                DataTable dt = new DataTable();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("select * from  Personal_Details where  Supplier= @Supplier", conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                cmd.Parameters.AddWithValue("@Supplier", supplier);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dt = ds.Tables[0];
                conn.Close();
                return dt;
            }
    
        }
     

    Tuesday, June 11, 2019 3:09 AM
  • User665608656 posted

    Hi Gopi.MCA,

    According to your code, I did a complete test with your code and it ran successfully without error warning.

    Could you please tell me the wrong information? This will help us solve your issue more easierly.

    Best Regards,

    YongQing.

    Tuesday, June 11, 2019 5:38 AM
  • User-807418713 posted
    Hello

    On page load the drop-down list not binding with any data it's showing plain no data is coming why
    Tuesday, June 11, 2019 5:50 AM
  • User665608656 posted

    Hi Gopi.MCA,

    I recommend you using F12 in the browser to debug your current code when you run it.

    You could refer this link :  https://msdn.microsoft.com/en-us/data/gg589530(v=vs.71)

    Check if there are any error reminders in the console of F12. You could give me a screenshot or description of the errors.

    Best Regards,

    YongQing.

    Tuesday, June 11, 2019 7:19 AM
  • User-807418713 posted

    Hello

    No Error But Data not showing in dropdownlist what it would be?

    i check cs code works fine

    I think the problem is in script aspx page

    why

    Tuesday, June 11, 2019 10:44 AM
  • User475983607 posted

    There are several confusing design issues.  The Web Methods return a string but the AJAX function is expecting JSON.  The Item and supplier are on the same record so I don't get the need to fill two selects from the same table.

    I recommend using strong types rather than DataSets and letting the framework handling the serialization.  Below is a tested example.

    Model

        public class PersonalDetails
        {
            private int _id;
            private string _supplier;
            private string _itemName;
            private double _rate;
    
            public int ID
            {
                get { return _id; }
                set { _id = value;  }
            }
    
            public string Supplier
            {
                get { return _supplier; }
                set { _supplier = value; }
            }
    
            public string ItemName
            {
                get { return _itemName; }
                set { _itemName = value; }
            }
    
            public double Rate
            {
                get { return _rate; }
                set { _rate = value; }
            }
    
        }

    Markup

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebFormsDemo._default" %>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link href="content/bootstrap.css" rel="stylesheet" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                SetDrop1();//bind dropdownlist1
                $("#DropDownList1").change(function () {
                    var selectedText = $(this).find(':selected').text();
                    SetDrop2(selectedText);
                });
                $("#DropDownList2").change(function () {
                    $("#TextBox1").val($("#DropDownList2").val());
                });
            })
            function SetDrop1() {
                $("#<%=DropDownList1.ClientID%>").empty();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/DropDownList1Bind",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = result.d;
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#<%=DropDownList1.ClientID%>").append("<option value='" + response[i]['ID'] + "'>" + response[i]['Supplier'] + "</option>");
                        }
                        SetDrop2($('#<%=DropDownList1.ClientID%> :selected').text());
                    }
                });
            }
    
            function SetDrop2(selectedText) {
                $("#<%=DropDownList2.ClientID%>").empty();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/DropDownList1Change",
                    data: '{supplier: "' + selectedText + '" }',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = result.d;
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#<%=DropDownList2.ClientID%>").append("<option value='" + response[i]['Rate'] + "'>" + response[i]['ItemName'] + "</option>");
                        }
                        $("#<%=TextBox1.ClientID %>").val($("#<%=DropDownList2.ClientID%>").val());
                    },
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
           </div>
           <div>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </div>
        </form>
    </body>
    </html>
    
    
    
    

    Code behind

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using WebFormsDemo.Models;
    
    namespace WebFormsDemo
    {
        public partial class _default : System.Web.UI.Page
        {
    
            protected void Page_Load(object sender, EventArgs e)
            {
                
    
            }
    
            [WebMethod]
            public static List<PersonalDetails>  DropDownList1Bind()
            {
                List<PersonalDetails> details = new List<PersonalDetails>();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM dbo.Personal_Details;", conn);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        PersonalDetails detail = new PersonalDetails();
                        detail.ID = (int)reader["ID"];
                        detail.Supplier = (string)reader["Supplier"];
                        detail.ItemName = (string)reader["ItemName"];
                        detail.Rate = (double)reader["Rate"];
                        details.Add(detail);
                    }
                    reader.Close();
                }
                conn.Close();
                return details;
            }
            [WebMethod]
            public static List<PersonalDetails> DropDownList1Change(string supplier)
            {
                List<PersonalDetails> details = new List<PersonalDetails>();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM dbo.Personal_Details WHERE Supplier = @Supplier;", conn);
                command.Parameters.AddWithValue("@Supplier", supplier);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        PersonalDetails detail = new PersonalDetails();
                        detail.ID = (int)reader["ID"];
                        detail.Supplier = (string)reader["Supplier"];
                        detail.ItemName = (string)reader["ItemName"];
                        detail.Rate = (double)reader["Rate"];
                        details.Add(detail);
                    }
                    reader.Close();
                }
                conn.Close();
                return details;
            }
    
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 11, 2019 2:10 PM
  • User-807418713 posted

    Hello

    No Data Is Binding To Dropdownlist So On F12 Console I Checked

    please see the screenshot why dropdownlist is not showing data

    Tuesday, June 11, 2019 4:54 PM
  • User475983607 posted

    I retested the example code and it is still functioning as expected.  You must be doing something wrong.  Double check your code or post the JavaScript if you need to community's support.

    Tuesday, June 11, 2019 5:35 PM
  • User665608656 posted

    Hi Gopi.MCA,

    According to the screenshots you provided, when you debugged F12, there was a real error.

    You can see the following picture where I marked it in red, which means there was an error on your page.

    To know what this error is, you need to click on the console tab to see it, just as click on the red marker in the picture below.

    When you click on the console tab, you could solve the issue according to the error prompt,or you could provide the error information to us.

    Best Regards,

    YongQing.

    Wednesday, June 12, 2019 12:52 AM
  • User-807418713 posted

    Hi

    The error is

    Default3.aspx:32 Uncaught TypeError: Cannot read property 'length' of undefined
    at Object.success (Default3.aspx:32)
    at b (jquery-1.4.2.min.js:122)
    at XMLHttpRequest.x.onreadystatechange (jquery-1.4.2.min.js:127)

    Wednesday, June 12, 2019 5:30 PM
  • User475983607 posted

    Your original code is using jQuery 3.2.1 the error is from jQuery 1.4.2.  Anyway the error, if you are using my code, is due to the second AJAX request returning zero records.

    Is there anyway you can share the source code that caused the error so we are not guessing?

    Wednesday, June 12, 2019 5:36 PM
  • User-807418713 posted

    Hello

    I Changed To This below code

       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>

    Again Error

    Uncaught TypeError: Cannot read property 'length' of undefined
    at Object.success (Default3.aspx:32)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

    Wednesday, June 12, 2019 5:42 PM
  • User475983607 posted

    Are you planning to post the source code any time soon? 

    Also, the error indicates two version of jQuery are loaded.

    Wednesday, June 12, 2019 5:44 PM
  • User-807418713 posted

    Hi

    Check The Error Screenshot in F12 Console

    Wednesday, June 12, 2019 5:59 PM
  • User475983607 posted

    Hi

    Check The Error Screenshot in F12 Console

    The error means response is undefined.  Which means there is something wrong with result.d.

    Posting all the source code is a pretty simple task.  I'm not sure why you're reluctance to do so.  There's not much else I can do for you without the source.  The example code I posted above has been verified for the third time.  You are doing something wrong.  

    Wednesday, June 12, 2019 6:13 PM
  • User-807418713 posted

    Hi...

    Thanks For Your Reply

    Here Is ASPX Code

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
    
     <!DOCTYPE html>
    
    <html lang="en">
    <head runat="server">
        <title>Untitled Page</title>
        
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                SetDrop1();//bind dropdownlist1
                $("#DropDownList1").change(function () {
                    var selectedText = $(this).find(':selected').text();
                    SetDrop2(selectedText);
                });
                $("#DropDownList2").change(function () {
                    $("#TextBox1").val($("#DropDownList2").val());
                });
            })
            function SetDrop1() {
                $("#DropDownList1").empty();
                $.ajax({
                    type: "POST",
                    url: "Default3.aspx/DropDownList1Bind",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = result.d;
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#DropDownList1").append("<option value='" + response[i]['ID'] + "'>" + response[i]['Supplier'] + "</option>");
                        }
                        SetDrop2($('#DropDownList1 :selected').text());
                    }
                });
            }
    
            function SetDrop2(selectedText) {
                $("#DropDownList2").empty();
                $.ajax({
                    type: "POST",
                    url: "Default3.aspx/DropDownList1Change",
                    data: '{supplier: "' + selectedText + '" }',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = result.d;
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#DropDownList2").append("<option value='" + response[i]['Rate'] + "'>" + response[i]['ItemName'] + "</option>");
                        }
                        $("#TextBox1").val($("#DropDownList2").val());
                    },
                });
            }
        </script>
        
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
           <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
            
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            
        </div>
        </form>
    </body>
    </html>
    

    Here Is ASPX.CS Code

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.Web.Services;
    using System.Configuration;
    using System.IO;
    using System.Text;
    
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        public class PersonalDetails
        {
            private int _id;
            private string _supplier;
            private string _itemName;
            private string _rate;
    
            public int ID
            {
                get { return _id; }
                set { _id = value; }
            }
    
            public string Supplier
            {
                get { return _supplier; }
                set { _supplier = value; }
            }
    
            public string ItemName
            {
                get { return _itemName; }
                set { _itemName = value; }
            }
    
            public string Rate
            {
                get { return _rate; }
                set { _rate = value; }
            }
    
        }
    
    
        [WebMethod]
        public static List<PersonalDetails> DropDownList1Bind()
        {
            List<PersonalDetails> details = new List<PersonalDetails>();
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
            SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM Personal_Details;", conn);
            conn.Open();
            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    PersonalDetails detail = new PersonalDetails();
                    detail.ID = (int)reader["ID"];
                    detail.Supplier = (string)reader["Supplier"];
                    detail.ItemName = (string)reader["ItemName"];
                    detail.Rate = (string)reader["Rate"];
                    details.Add(detail);
                }
                reader.Close();
            }
            conn.Close();
            return details;
        }
    
    
        [WebMethod]
        public static List<PersonalDetails> DropDownList1Change(string supplier)
        {
            List<PersonalDetails> details = new List<PersonalDetails>();
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
            SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM dbo.Personal_Details WHERE Supplier = @Supplier", conn);
            command.Parameters.AddWithValue("@Supplier", supplier);
            conn.Open();
            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    PersonalDetails detail = new PersonalDetails();
                    detail.ID = (int)reader["ID"];
                    detail.Supplier = (string)reader["Supplier"];
                    detail.ItemName = (string)reader["ItemName"];
                    detail.Rate = (string)reader["Rate"];
                    details.Add(detail);
                }
                reader.Close();
            }
            conn.Close();
            return details;
        }
    }
    

    Thank You

    Wednesday, June 12, 2019 6:17 PM
  • User-807418713 posted

    Hi

    Please Check This First Record? Whats The Issue

    Wednesday, June 12, 2019 6:28 PM
  • User475983607 posted

    You changed the connection string name from ConnectionString to MyConnectionString.  You must have also changed the Rate data type in SQL from a float to a string.  This is reflected in the response image shown.

    I'm getting 500 error with your changed code!

    Once I change the Db type to a VARCHAR the code starts working again.  Clearly, you are making changes without letting us know.  I have no idea what error or issue goes with the current code base.

    Wednesday, June 12, 2019 6:46 PM
  • User665608656 posted

    Hi Gopi.MCA,

    According to the code you provided and the code provided by mgebhard,did you change the database connection ?

    Because I found that your connection changed, and according to the SQL statement provided in your initial question, Rate in the datasheet should be float type, but your code changed to string type, which led to errors when we used your code.

    But when we changed the Rate field type to varchar, we used your code again. There is no problem with testing.

    I recommend that you make sure you can connect to the corresponding datasheet, and then make sure that the field types in the datasheet are the same as those in your code.

    Best Regards,

    YongQing.

    Thursday, June 13, 2019 1:26 AM
  • User-807418713 posted
    Hello

    I have change connection string name for my reference its loading data already screenshoot share

    Second i change rate column as well again its not binding is that any other code can be be achive this sceniro please check this screenshot why its showing wrong


    http://i64.tinypic.com/e5nwi1.png
    Thursday, June 13, 2019 4:10 AM
  • User665608656 posted

    Hi Gop.MCA,

    I suggest that you try to return a JSON string to the foreground in the webmethod, and then use JSON.parse in JS to convert the JSON string into object.

    Here are detailed code:

    <!DOCTYPE html>
    
    <html>
    <head runat="server">
        <title>Untitled Page</title>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                SetDrop1();//bind dropdownlist1
                $("#DropDownList1").change(function () {
                    var selectedText = $(this).find(':selected').text();
                    SetDrop2(selectedText);
                });
                $("#DropDownList2").change(function () {
                    $("#TextBox1").val($("#DropDownList2").val());
                });
            })
            function SetDrop1() {
                $("#DropDownList1").empty();
                $.ajax({
                    type: "POST",
                    url: "WebForm_0613_2156419.aspx/DropDownList1Bind",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = JSON.parse(result.d);
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#DropDownList1").append("<option value='" + response[i]['ID'] + "'>" + response[i]['Supplier'] + "</option>");
                        }
                        SetDrop2($('#DropDownList1 :selected').text());
                    }
                });
            }
    
            function SetDrop2(selectedText) {
                $("#DropDownList2").empty();
                $.ajax({
                    type: "POST",
                    url: "WebForm_0613_2156419.aspx/DropDownList1Change",
                    data: '{supplier: "' + selectedText + '" }',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var response = JSON.parse(result.d);
                        console.log(response);
                        for (var i = 0; i < response.length; i++) {
                            $("#DropDownList2").append("<option value='" + response[i]['Rate'] + "'>" + response[i]['ItemName'] + "</option>");
                        }
                        $("#TextBox1").val($("#DropDownList2").val());
                    },
                });
            }
        </script>
    
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
    
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    
            </div>
        </form>
    </body>
    </html>
    

    code behind:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1.Cases
    {
        public partial class WebForm_0613_2156419 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            public class PersonalDetails
            {
                private int _id;
                private string _supplier;
                private string _itemName;
                private double _rate;
    
                public int ID
                {
                    get { return _id; }
                    set { _id = value; }
                }
    
                public string Supplier
                {
                    get { return _supplier; }
                    set { _supplier = value; }
                }
    
                public string ItemName
                {
                    get { return _itemName; }
                    set { _itemName = value; }
                }
    
                public double Rate
                {
                    get { return _rate; }
                    set { _rate = value; }
                }
    
            }
    
    
            [WebMethod]
            public static string DropDownList1Bind()
            {
                List<PersonalDetails> details = new List<PersonalDetails>();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM Personal_Details;", conn);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        PersonalDetails detail = new PersonalDetails();
                        detail.ID = (int)reader["ID"];
                        detail.Supplier = (string)reader["Supplier"];
                        detail.ItemName = (string)reader["ItemName"];
                        detail.Rate = (double)reader["Rate"];
                        details.Add(detail);
                    }
                    reader.Close();
                }
                conn.Close();
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string myJson = jss.Serialize(details);
                return myJson;
            }
    
    
            [WebMethod]
            public static string DropDownList1Change(string supplier)
            {
                List<PersonalDetails> details = new List<PersonalDetails>();
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand command = new SqlCommand("SELECT ID, Supplier, ItemName, Rate FROM dbo.Personal_Details WHERE Supplier = @Supplier", conn);
                command.Parameters.AddWithValue("@Supplier", supplier);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        PersonalDetails detail = new PersonalDetails();
                        detail.ID = (int)reader["ID"];
                        detail.Supplier = (string)reader["Supplier"];
                        detail.ItemName = (string)reader["ItemName"];
                        detail.Rate = (double)reader["Rate"];
                        details.Add(detail);
                    }
                    reader.Close();
                }
                conn.Close();
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string myJson = jss.Serialize(details);
                return myJson;
            }
    
        }
    }

    If this method still does not solve your issue, please use F12 to show me the value of result.d?

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 13, 2019 9:10 AM
  • User-807418713 posted

    Hello

    1) How to get the value of result.d? to check whats the data?

    2) The Above Code Works In ASp.net 2.0 C# or not?

    Error Below

    VM43:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.success (Default3.aspx:30)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

    Thursday, June 13, 2019 9:23 AM
  • User475983607 posted

    Gopi.MCA

    2) The Above Code Works In ASp.net 2.0 C# or not?

    The error is in the browser.

    The error indicates two different version of jQuery are loaded but the code shown does not reflect two different versions.  Are you sure you are showing us the actual runtime code?

    Thursday, June 13, 2019 10:49 AM
  • User-807418713 posted

    Hi Mgebhard

    I tried other browser as well 

    Screenshot of the error as below

    <form>
     
    </form>
    Thursday, June 13, 2019 10:58 AM
  • User475983607 posted

    The error message indicates two different version of jQuery.  Are you loading other jQuery libraries?

    It is very hard to help you because you keep changing the code without posting the changes. 

    Thursday, June 13, 2019 11:12 AM
  • User-807418713 posted

    Hi Mgebhard

    Thank You For Your Reply

    Thank You For Your Continues Support Mgebhard And Yongqing Yu

    Thursday, June 13, 2019 11:30 AM