我有一个下载列表,现在已加载数据我想更改按钮点击下拉列表的选定项目,该项目从webservice提供Id。
以下是我的网络方法:
[WebMethod]
public string EditData(int sid) //Show the edit clicked data in the popup window
{
string jsondata;
//var details = new List<Employee>();
DataTable dt = bllsubcat.GetSubCategoryById(sid);
jsondata = JsonConvert.SerializeObject(dt);
return jsondata;
}
这是我的ajax电话:
$(document).on("click", ".editButton", function () {
$('#myModal').focus();
var id = $(this).attr("data-id");
console.log(id);
$("#btnUpdate").attr("edit-id", id);
//alert(id); //getting the row id
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "SubCategoryService.asmx/EditData",
data: '{sid: ' + id + '}',
dataType: "json",
success: function (data) {
var subcatdet = $.parseJSON(data.d);
$.each(subcatdet, function (index, value) {
$("#ddlCategory1").val(value.CategoryName);
$("#txtSubCatName1").val(value.SubCategoryName);
});
},
error: function () {
alert("Error while retrieving data of :" + id);
}
});
});
从上面的代码
$("#txtSubCatName1").val(value.SubCategoryName);
$("#ddlCategory1").val(value.CategoryName);
成功地将值加载到文本框,但选定的下拉项不会更改。
以下是我加载下拉列表的代码:
<asp:DropDownList ID="ddlCategory1" runat="server"></asp:DropDownList>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SubCategoryService.asmx/LoadCategory",
data: "{}",
dataType: "json",
success: function (r) {
var ddlCategory = $("[id*=ddlCategory1]");
ddlCategory.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
ddlCategory.append($("<option></option>").val(this['CategoryId']).html(this['CategoryName']));
});
},
error: function (Result) {
alert("Error");
}
});
});
</script>
答案 0 :(得分:0)
要按照您的方式设置选项值,您的选项应具有价值,如下所示:
<select id="ddlCategory1">
<option value="1">Food</option>
<option value="2" selected="1">Clothes</option>
<option value="3">Drinks</option>
</select>
在asp.net c#后面的代码可以是这样的:
ddlCategory1.DataTextField = "CategoryName";
ddlCategory1.DataValueField = "CategoryID";
然后按类别ID(不是名称)选择它们:
$("#ddlCategory1").val(value.CategoryID);
另一种选择是按选项的文字选择:
$('#ddlCategory1 option').filter(function() {
return ($(this).text() == value.CategoryName);
}).prop('selected', true);