如何将反序列化JSON中的列表传递给视图到选择列表

问题描述 投票:0回答:1

我为我的公司设置了一个应用程序,但我在编程方面相对较新。现在我想尝试与API - >获取值 - >将值传递到选择列表 - >使列表重定向到另一个页面。现在我遇到一个问题,将值从我的控制器传递到视图中的选择列表。我用Google搜索了如何设置选择列表以及如何使用列表填充它但我似乎无法弄明白。我需要朝着正确的方向努力。我究竟做错了什么。我的课:

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>
c# asp.net-core model-view-controller
1个回答
1
投票

你的List<string> GetLeafSwitchProfiles方法返回Liststring。通过在Controller中添加以下内容将列表转换为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>
© www.soinside.com 2019 - 2024. All rights reserved.