在ASP.NET Core中实现级联选择可以使用JavaScript库来处理客户端的逻辑,并使用ASP.NET Core提供的API来处理服务器端的逻辑。下面是一个使用jQuery和ASP.NET Core的级联选择示例:
首先,将必要的库文件添加到项目中。你可以使用CDN或者将库文件下载到本地。
接下来,创建一个包含级联选择的HTML表单。在这个例子中,我们有两个下拉列表,一个用于选择国家,另一个用于选择城市。
接下来,使用JavaScript来实现级联选择的逻辑。在选择国家后,发送Ajax请求到服务器获取相应的城市列表,并更新城市下拉列表的选项。
$(document).ready(function () {
$('#country').change(function () {
var countryId = $(this).val();
if (countryId) {
$.ajax({
url: '/api/cities/' + countryId,
type: 'GET',
success: function (data) {
$('#city').removeAttr('disabled');
$('#city').empty();
$('#city').append('');
$.each(data, function (index, city) {
$('#city').append('');
});
}
});
} else {
$('#city').attr('disabled', 'disabled');
$('#city').empty();
$('#city').append('');
}
});
});
最后,在ASP.NET Core中创建一个API控制器来处理请求并返回城市列表。在这个例子中,我们使用了硬编码的城市数据。
[Route("api/cities")]
[ApiController]
public class CitiesController : ControllerBase
{
[HttpGet("{countryId}")]
public IActionResult GetCities(int countryId)
{
List cities = new List();
// Hardcoded city data for demonstration purposes
if (countryId == 1)
{
cities.Add(new City { Id = 1, Name = "New York" });
cities.Add(new City { Id = 2, Name = "Los Angeles" });
}
else if (countryId == 2)
{
cities.Add(new City { Id = 3, Name = "Toronto" });
cities.Add(new City { Id = 4, Name = "Vancouver" });
}
return Ok(cities);
}
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
以上就是一个简单的ASP.NET Core中的级联选择示例。当选择国家时,城市下拉列表将被禁用,并从服务器获取相应的城市列表,然后将选项添加到城市下拉列表中。