我从一个创建列表的API中获取了一些数据,但是当我尝试在.cshtml文件中循环浏览列表时,它什么也没有显示,并且列表的计数为0。但是当我循环浏览时它确实显示结果的OnGetAsync()方法中的列表。
我尝试了不启用异步功能,并尝试在getDataAsync()方法中填充列表。
public IList<Employee> Employee = new List<Employee>();
public async void OnGetAsync()
{
// Sets up HttpClient
await RunAsync();
// API call method which returns a list filled with the results
Employee = await GetDataAsync("api-url");
// Shows Results!
foreach (var item in Employee)
{
Debug.WriteLine(item.name);
}
}
static async Task<List<Employee>> GetDataAsync(string path)
{
string data = null;
List<Employee> list = new List<Employee>();
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsStringAsync();
}
JObject json = JObject.Parse(data);
// Get the only the data i need from the entire json api result
foreach (var d in json["data"])
{
string setId;
string setName;
string setUrl;
if (d["id"] == null)
{
setId = "NA";
} else
{
setId = d["id"].ToString();
}
if (d["person"]["full_name"] == null)
{
setName = "NA";
} else
{
setName = d["person"]["full_name"].ToString();
}
if (d["avatar"]["url_small"] == null)
{
setUrl = "NA";
} else
{
setUrl = d["avatar"]["url_small"].ToString();
}
list.Add(new Employee
{
id = setId,
name = setName,
avatar_url = setUrl
});
}
Debug.Unindent();
return list;
}
<!-- Shows 0 -->
<p>@Model.Employee.Count</p>
<!-- Shows nothing -->
@foreach (var item in Model.Employee)
{
<p>@Html.DisplayFor(modelItem => item.name)</p>
}
我希望能够遍历列表并在网页上显示结果,而不是列表的计数为0,并且什么都没有显示。
答案 0 :(得分:1)
代码中的问题是OnGetAsync
是一个异步方法,当您返回Task
时应该返回void
只需更改其返回类型。
public async Task OnGetAsync()
{
// Your code here
}