One way to populate your dropdown lists is by using ViewData.
Let's assume that your calls to the API reside in a separate service. The API would need to return a List. In this example the List will be of a custom class: List<CustomClass>
. Let's assume that your custom class contains a property Id
, and a property Name
. Your controller would look like:
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();
}
}
Now, to populate the dropdowns in your View:
<select asp-items="ViewBag.DataFromArticle1"></select>
<select asp-items="ViewBag.DataFromArticle2"></select>
UPDATE
The following code will call your API endpoint by AJAX. We assume that you have created a WebApi
, and that within your WebAPI
you have an ArticleDataController
with a method called GetDataFromArticle1
.
Your view:
<select id="dataFromArticle1"></select>
Your 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);
}
});
});