Bind DropDownList with SQL Server Data using .ajax() jQuery Method and WCF Service

This blog is containing detailed information about DropDownList with jQuery. To Bind DropDownList in jQuery  We have to write below code in <script> block.

<script type="text/javascript">

    function CallService() {

        var txtValue = $("#TextBox1").val();

        $.ajax({

            type: "POST", //GET or POST or PUT or DELETE verb

            url: "Service.svc/getCityList", // Location of the service

            data: '{"str": "' + txtValue + '"}', //Data sent to server

            contentType: "application/json; charset=utf-8", // content type sent to server

            dataType: "json", //Expected data format from server

            processdata: true, //True or False

            success: function (msg) {//On Successfull service call

                if (msg.getCityListResult == '') {

                    $("#divCity").html("No Data found");

                }

                else {

                    var ddl = $('#ddlCity');

                    ddl.append("<option value='0'>-select-</option>");

                    for (var i = 0; i < msg.getCityListResult.length; i++) {

                        var City = msg.getCityListResult[i].split('~')[0];

                        var Code = msg.getCityListResult[i].split('~')[1];

                        ddl.append("<option value='" + Code + "'>" + City + "</options>");

                    }

                }

            }

        });

    }

</script>

With the above code you get all city name and code against State name.
If the state name not exist in the database,

divCity(div id) shows "No Data found".

Write below code in WCF .cs file

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.ServiceModel.Activation;

using System.Data.SqlClient;

using System.Data;

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config.

[AspNetCompatibilityRequirements(RequirementsMode =

AspNetCompatibilityRequirementsMode.Allowed)]

public class Service : IService

{

SqlConnection cn = new SqlConnection("Data Source=BCILGGN13\\SQLEXPRESS;

Initial Catalog=Test; Uid=sa; Pwd=bcil; ");

SqlDataAdapter adap;

DataTable dt;

public List<string> getCityList(string State)

{

List<string> objList = new List<string>();

adap = new SqlDataAdapter("select city,count from City_List where State='" + State.Trim() + "'", cn);

dt = new DataTable();

adap.Fill(dt);

if (dt.Rows.Count > 0)

{

for (int i = 0; i < dt.Rows.Count; i++)

{

objList.Add(dt.Rows[i]["city"].ToString() + "~" + dt.Rows[i]["count"].ToString());

}

}

return objList;

}

}

Write below code in .aspx file

I called the CallService() function on textbox onblur event.

<body>

<form id="form1" runat="server">

<div>

Enter State Name :-

<asp:TextBox ID="TextBox1" runat="server" onblur="CallService();"></asp:TextBox>

</div>

<br />

<br />

<br />

<div id="divCity" style="width: 200px; height: 50px;">

</div>

City List : -

<select id="ddlCity">

</select>

</form>

</body>

Write below code in Iservice.cs file

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.ServiceModel.Web;

using System.ServiceModel.Activation;

using System.Data;

// NOTE: If you change the interface name "IService" here, you must also

update the reference to "IService" in Web.config.

[ServiceContract]

public interface IService

{

[OperationContract]

[WebInvoke(Method = "POST",

BodyStyle = WebMessageBodyStyle.Wrapped,

ResponseFormat = WebMessageFormat.Json)]

List<string> getCityList(string str);

}

  
Table in SQL Server containing below data. .

Note :- WCF service method always return Collection type. Please find enclosed attachment to see further information.

Ebook Download
View all
Learn
View all