我有2个下拉列表城市和州以及邮政编码文本框。我需要根据输入的邮政编码生成城市和州的下拉列表。当用户输入邮政编码时,我会将邮政编码传递给我的API以获取州/城市列表。 使用下面的代码,我能够从我的API中获取数据,并且可以在控制台中看到州/城市,但是我无法在下拉菜单中显示。我不确定我缺少什么。如何在淹没列表中显示数据。
API控制器:
public class Getstatelist : ApiController
{
// GET api/Getstatelist/5
public List<CityState> GetCityState(string zipEntered)
{
var list = new List<CityState>();
if (string.IsNullOrEmpty(zipEntered) || zipEntered.Length < 2)
return list;
zipEntered += "%";
using (var connection = new OracleConnection(ConfigurationManager.ConnectionStrings["MY_DB_CONNECTION_STRING"].ConnectionString))
{
connection.Open();
var sqlQuery = "select state from state_city_data where zip like :zipEntered";
using (var command = new OracleCommand(sqlQuery, connection))
{
command.BindByName = true;
command.Parameters.Add("zipEntered", OracleDbType.Varchar2).Value = zipEntered;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
list.Add(new CityStateZip
{
State = reader["STATE"] != DBNull.Value ? Convert.ToString(reader["STATE"]) : null,
});
}
}
}
}
return list;
}
}
$(document).ready(function ()
{
$("#zip").keyup(function () {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
type:'GET',
url: "../api/Getstatelist/" + el.val(),
success: function (html) {
console.log(html);
$('#state').html(html);
}
});
}else{
$('#state').html('<option value="">Enter Zip code first </option>');
}
});
});
<div>
<div class="city-wrap">
<select id="city">
<option value="">Select City first</option>
</select>
<label for="city">City</label>
</div>
<div class="state-wrap">
<select id="state">
<option value="">Select State </option>
</select>
<label for="state">State</label>
</div>
<div class="zip-wrap">
<input type="text" pattern="[0-9]*" maxlength="5" required name="zip" id="zip" >
<label for="zip">Zip</label>
</div>
</div>
答案 0 :(得分:1)
要填充状态下拉列表,您需要按以下方式修改ajax中的成功回调:
$.each(html,function(key,value){
$('#state').append($('<option></option>').val(value.State).html(value.State));
});
对于城市下拉菜单也是如此:
$.each(html,function(key,value){
$('#city').append($('<option></option>').val(value.City).html(value.City));
});