Earlier I explained Binding DropDownList with jQuery and Wcf service. Now I am going to explain DropDownList with jQuery and web service. To Bind DropDownList in jQuery We have to write below code in <script> block.
function
GetBatchInfo(ProductName) {
var getBatch =
"WebService.asmx/GetBatchGodwn";
$.ajax({
type: "POST",
url: getBatch,
data: "{'ProductName': '" + ProductName + "' }",
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (response) {
$("select[id$=ddlBatch] > option").remove();
var models = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
var ddl = $('#ddlBatch');
ddl.append("<option value='0'>-select Batch-</option>");
for (var i = 0; i < models.length; i++) {
var val = models[i].Batch + " ( " + models[i].StoreGodwn + " ) ";
var text = models[i].Batch;
ddl.append("<option value='" + text + "'>" + val + "</option>");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
Suppose I have a table which contain two columns names batch and, godown. With
the above code you get batchno and godown information. Write below code in Web
service.
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
SqlDataAdapter adap;
DataTable dt;
SqlConnection cn = new SqlConnection(Common.GetConnectionString());
public WebService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public List<getBatch> GetBatchGodwn(string ProductName)
{
List<getBatch> objgetBatch = new List<getBatch>();
adap = new SqlDataAdapter("SP_GET_BATCH_GODOWN", cn);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
adap.SelectCommand.Parameters.AddWithValue("@ProductName", ProductName);
dt = new DataTable();
adap.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objgetBatch.Add(new getBatch
{
Batch = dt.Rows[i]["Batch"].ToString(),
StoreGodwn = dt.Rows[i]["Name"].ToString()
}
);
}
}
return objgetBatch;
}
}
Note :- Web service method always return Collection type.

Join the conversation! Your thoughts help the community grow.