填充下拉列表的一种方法是使用 ViewData。
假设您对 API 的调用驻留在单独的服务中。 API 需要返回一个列表。在此示例中,列表将属于自定义类:List<CustomClass>。假设您的自定义类包含一个属性Id 和一个属性Name。你的控制器看起来像:
public class HomeController : Controller
{
private readonly IApiService _apiService;
public HomeController(
IApiService apiService)
{
_apiService = apiService;
}
public IActionResult Index()
{
// Get the data from the API into the ViewData
// In this example, Id will be the Id of the dropdown option,
// and the Name will be what's displayed to the user
ViewData["DataFromArticle1"] = new SelectList(
await _apiService.GetDataFromArticle1Async(),
"Id", "Name");
ViewData["DataFromArticle2"] = new SelectList(
await _apiService.GetDataFromArticle2Async(),
"Id", "Name");
return View();
}
}
现在,在您的视图中填充下拉列表:
<select asp-items="ViewBag.DataFromArticle1"></select>
<select asp-items="ViewBag.DataFromArticle2"></select>
更新
以下代码将通过 AJAX 调用您的 API 端点。我们假设您已经创建了一个WebApi,并且在您的WebAPI 中您有一个ArticleDataController 和一个名为GetDataFromArticle1 的方法。
你的看法:
<select id="dataFromArticle1"></select>
你的 JavaScript:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/ArticleData/GetDataFromArticle1",
success: function (data) {
var s = '<option value="-1">Please Select a Department</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].Id+ '">' + data[i].Name + '</option>';
}
$("#dataFromArticle1").html(s);
}
});
});