【发布时间】:2021-10-09 09:50:07
【问题描述】:
在我的 ASP.NET Core 3.1 应用程序中,我正在使用 jQuery 实现级联 DropDown 功能。第一个 DropDown (Region) 的值更改应填充第二个 DropDown,位置。更改 ddlRegion 的值时,jQuery 正确地点击了 Controller 方法,并且还在 json 列表中返回了结果,但是第二个 DropDown 中的结果被填充为“未定义”。
[下拉 HTML]
<table style="margin-left:2%;margin-top:2%">
<tr style="width:200px">
<td style="width:100px">Region</td>
<td style="width:300px">
@Html.DropDownList("DDLRegion", new List<SelectListItem>
{
new SelectListItem{ Text="-- Select --", Value = "0" },
new SelectListItem{ Text="North", Value = "1" },
new SelectListItem{ Text="South", Value = "2" },
new SelectListItem{ Text="All", Value = "3" }
}, new { @id = "DDLRegion" })
</td>
<td style="width:100px">Location</td>
<td style="width:300px">
@Html.DropDownList("DDLLocation", new List<SelectListItem>
{
new SelectListItem{ Text="-- Select --", Value = "0" },
}, new { @id = "DDLLocation" })
</td>
</tr>
</table>
[jQuery 代码]
$(document).ready(function () { $("#DDLRegion").change(function () {
$("#DDLLocation").empty();
$.ajax({
type: 'GET',
url: '/GetLocations/1',
dataType: 'json',
data: { id: $("#DDLRegion").val() },
success: function (locationsList) {
$.each(locationsList, function (i,location) {
$('#DDLLocation').append('<option value="'
+ location.Value + '">' +
location.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve locations');
}
});
return false;
})
});
[控制器代码]
[Route("~/GetLocations/{id}")]
public JsonResult GetLocations(string id)
{
List<SelectListItem> locations =
new List<SelectListItem>();
int counter = 0;
string line;
locations.Add(new SelectListItem
{
Text = "Select",
Value = "0"
});
switch (id)
{
case "1":
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(@"North_Locations.txt");
while ((line = file.ReadLine()) != null)
{
locations.Add(new SelectListItem { Text = line, Value = counter.ToString() });
counter++;
}
file.Close();
counter = 0;
line = "";
break;
case "2":
// Read the file and display it line by line.
System.IO.StreamReader file2 =
new System.IO.StreamReader(@"South_Locations.txt");
while ((line = file2.ReadLine()) != null)
{
locations.Add(new SelectListItem { Text = line, Value = counter.ToString() });
counter++;
}
file2.Close();
counter = 0;
line = "";
break;
}
return Json(new SelectList(locations,
"Value", "Text"));
}
}
在 jQuery 代码中,“位置”是未定义的。如果控制器返回 80 个项目,则位置下拉列表将填充 80 个“未定义”。
【问题讨论】:
-
结果行似乎没有 Text 属性。您需要检查返回 json。
-
可能跑题了:你的 url 应该是
url: '/GetLocations/1',而不是url: '/GetLocations,,因为你将 id 作为数据传递,所以无论区域如何,它都将始终是1。跨度> -
我怀疑序列化程序使用 camelCase。试试
append('<option value="' + location.value + '">' + location.text + '</option>'); -
"它有
Text" ... "它适用于text" - 这些不一样 - 这是为什么我们要求查看实际值,而不是只信守诺言。 -
我编辑了@Izzy 答案以添加此信息。你能接受他的回答吗?
标签: javascript c# jquery json asp.net-core