根据您的描述,您似乎想根据所选API显示相关的Endpoints选项,如果是这种情况,您可以参考以下代码(我假设您已经创建了Asp.net Core Razor页面申请):
基于config json文件,创建如下类:
public class APIS
{
public int APIID { get; set; }
public string APIName { get; set; }
public bool Enabled { get; set; }
public int APIPort { get; set; }
public List<Endpoints> Endpoints { get; set; }
}
public class Endpoints
{
public int ID { get; set; }
public bool Enabled { get; set; }
public string FriendlyName { get; set; }
public string Mapping { get; set; }
}
在 Index.cshtml.cs 文件中:
[BindProperty]
public List<APIS> APIS { get; set; }
public void OnGet()
{
APIS = apiservice.GetAllAPI(); //get all API and the related endpoints.
}
[BindProperty(SupportsGet = true)]
public string apiname { get; set; }
public JsonResult OnGetGetEndPoints()
{
APIS = apiservice.GetAllAPI(); //get all API and the related endpoints.
return new JsonResult(APIS.Where(c => c.APIName == apiname).Select(c => c.Endpoints).ToList());
}
Index.cshtml 页面中的代码(endpoints div 用于填充端点。):
<div >
<div class="col-md-6">
<div class="">
<h2>Please select API</h2>
@foreach (var item in Model.APIS)
{
<input type="radio" id="radio_@item.APIName" class="radio_api" data-apiname="@item.APIName" name="APIName" /> @item.APIName
}
</div>
</div>
<div class="col-md-6">
<div class="">
<h2>Please select Endpoints</h2>
<div id="endpoints">
</div>
</div>
</div>
</div>
JavaScript 代码:
@section Scripts{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(function () {
$(".radio_api").each(function (index, item) {
$(item).click(function () {
var apiname = $(this).attr("data-apiname");
//using getJson method:
$.getJSON(`?handler=GetEndPoints&apiname=${apiname}`, (data) => {
$("#endpoints").html(""); //clear the container.
$.each(data[0], function (key, value) {
$("#endpoints").append(`<input type="radio" name="endpoint"/>${value.friendlyName}`);
});
});
});
});
});
</script>
}
此外,您还可以创建 API 并使用 JQuery Ajax 调用 API 方法并加载端点:
$.ajax({
url: "api/values?apiname=" + apiname,
type: 'Get',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (exception) {
console.log(exception);
},
success: function (result) {
//console.log("Success");
$("#endpoints").html("");
$.each(result[0], function (key, value) {
$("#endpoints").append(`<input type="radio" name="endpoint"/>${value.friendlyName}`);
});
}
});
截图如下:
参考:https://www.learnrazorpages.com/razor-pages/ajax/cascading-dropdowns