我为我的公司设置了一个应用程序,但在编程方面相对较新。现在,我尝试使用API->获取值->将值传递到选择列表中->使列表重定向到另一个页面。现在我遇到了一个问题,即将值从控制器传递到视图中的选择列表。香港专业教育学院谷歌如何设置选择列表,以及如何用列表填充它,但我似乎无法弄清楚。我需要朝着正确的方向前进。我究竟做错了什么。 我的班级:
public class ApiCalls
{
Login login = new Login();
public List<string> GetLeafSwitchProfiles()
{
string token = login.Apilogin();
var client = new RestClient("https://10.23.175.1/api/node/mo/uni/infra.json?query-target=subtree&target-subtree-class=infraNodeP");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddCookie("APIC-cookie", token);
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
LeafSwitchesProfileModel.Rootobject rootobject = (LeafSwitchesProfileModel.Rootobject)JsonConvert.DeserializeObject<LeafSwitchesProfileModel.Rootobject>(response.Content);
List<string> leafprofiles = new List<string>();
foreach (var num in rootobject.imdata)
{
//leafprofiles.Add(num.infraNodeP.attributes.name);
string name = num.infraNodeP.attributes.name;
leafprofiles.Add(name);
}
return leafprofiles;
}
else
{
return null;
}
}
}
我的控制器:
public IActionResult Index()
{
//Pick switch
ApiCalls apiCalls = new ApiCalls();
ViewBag.test = apiCalls.GetLeafSwitchProfiles();
return View();
}
我的观点:
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
@foreach (var item in ViewBag.test)
{
<h2>@item.Name</h2>
}
</div>
答案 0 :(得分:1)
您的List<string> GetLeafSwitchProfiles
方法返回List
中的string
。通过在控制器中添加以下内容,将列表转换为IEnumerable<SelectListItem>
:
public IActionResult Index()
{
//Pick switch
ApiCalls apiCalls = new ApiCalls();
ViewBag.test = new SelectList(apiCalls.GetLeafSwitchProfiles());
return View();
}
现在,通过以下方式填充您的SelectList:
<select asp-items="ViewBag.test"></select>