3 回答
TA贡献1844条经验 获得超8个赞
试试这个,你正在设置值,你没有为选项标签设置文本,你必须得到空白菜单项。已经使用你的数据链接和代码对其进行了测试。
s += '<option value="' + jsonRes[i].Id+ '">'+jsonRes[i].Id + '</option>';
完整的 HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select class="dropdown" id="dropdownData"></select>
<script>
$(document).ready(function () {
$.ajax({
url: "https://api.myjson.com/bins/6jd1s",
type: 'GET',
success: function (jsonRes) {
console.log(jsonRes[i]);
var s = '<option value="-1">Please Select</option>';
for (var i = 0; i < jsonRes.length; i++) {
s += '<option value="' + jsonRes[i].Id+ '">'+jsonRes[i].Id + '</option>';
}
$("#dropdownData").html(s);
}
});
});
</script>
</body>
</html>
TA贡献1921条经验 获得超9个赞
删除行 string jsonRes = JsonConvert.SerializeObject(data);
您的方法 GetdData() 也应该返回 JSON。检查以下代码。
public ActionResult GetData(Tablet tablet)
{
List<Tablet> data = new List<Tablet>();
data.Add(new Tablet() { Id = 1, Country = "India", Description = "Test", ManufactureDate = DateTime.UtcNow.ToShortDateString() });
data.Add(new Tablet() { Id = 1, Country = "Canada", Description = "Test1", ManufactureDate = DateTime.UtcNow.ToShortDateString() });
//string jsonRes = JsonConvert.SerializeObject(data);
return Json(data,JsonRequestBehavior.AllowGet);
}
视图应该像
<select class="dropdown" id="dropdownData"></select>
<script>
$(document).ready(function () {
$.ajax({
url: "/Home/GetData/",
type: 'GET',
dataType: "json",
success: function (jsonRes) {
console.log(jsonRes[i]);
var s = '<option value="-1">Please Select</option>';
for (var i = 0; i < jsonRes.length; i++) {
s += '<option value="' + jsonRes[i].Id + '">' + jsonRes[i].Id+ '</option>';
}
$("#dropdownData").html(s);
}
});
});
</script>
TA贡献1831条经验 获得超10个赞
尝试这个:
数据控制器:
[HttpGet]
public JsonResult GetData()
{
List<Tablet> data = new List<Tablet>();
// ... Code to retrieve the data from your API
string jsonRes = JsonConvert.SerializeObject(data);
return new JsonResult(jsonRes);
}
在你的 JavaScript 中:
$.ajax({
url: "/Data/GetData/",
type: "GET",
dataType: "json",
cache: false,
success: function (data) {
try {
var parsedData = JSON.parse(data);
var $select = $('#dropdownData');
$.each(parsedData, function(i, dataItem) {
$('<option>', {
value: dataItem.Id
}).html(dataItem.Id).appendTo($select); // or dataItem.Description, or whatever field you want to display to the user
});
}
catch (err) {
console.log(err);
}
}
},
error: function (e) {
console.log(e);
}
});
- 3 回答
- 0 关注
- 136 浏览
添加回答
举报