我有级联下拉菜单。在选择一个下拉列表时,另一个下拉列表使用ajax绑定。这完全有效,但我希望第二个下拉列表还应该包含默认文本和值('选择我')。如何添加此默认值。这是我的代码。
function BindCities(drpstate) {
var stateid = $(drpstate).val();
$.ajax({
url: '/Register.aspx/BindCities',
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"id":"' + stateid + '"}',
success: function (result) {
var drpcity = $('.drpcity');
drpcity.empty();
$.each(result.d, function () {
drpcity.append(
$('<option/>', {
value: this.id,
text: this.name
})
);
});
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
HTML:
<asp:DropDownList runat="server" CssClass="drpstate" onchange="BindCities(this)" ID="drpdwnState">
<asp:ListItem Text="Select State" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList runat="server" CssClass="drpcity" ID="drpdwnCity">
<asp:ListItem Text="Select City" Value="0"></asp:ListItem>
</asp:DropDownList>
服务器端代码:
[WebMethod]
public static List<CountryState> BindCities(int id)
{
EkbnManager em = new EkbnManager();
List<City> cities = em.GetCityByStateId(id);
List<CountryState> countrystate = new List<CountryState>();
foreach (var item in cities)
{
CountryState cnt = new CountryState();
cnt.name = item.Name;
cnt.id = item.Id;
countrystate.Add(cnt);
}
return countrystate;
}
答案 0 :(得分:1)
成功功能是这样的:
success: function (result) {
var drpcity = $('.drpcity');
drpcity.empty();
drpcity.append(
$('<option/>', {
value: -1,
text: please select one
})
$.each(result.d, function () {
drpcity.append(
$('<option/>', {
value: this.id,
text: this.name
})
);
});
答案 1 :(得分:-1)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/GetMethod",
data: "",
dataType: "json",
success: function (data) {
$("#drpName").empty();
$("<option value='-1'>(Select item)</option>").appendTo("#drpName");
$.each(data.d, function (key, value) {
$("#drpName").append($("<option></option>").val(value.ID).html(value.Title));
});
},
error: function (result) {
alert("Could not get!");
}
});