I'm creating web-client for my REST API, and I want to add a field to my table containing result of async function.
@foreach(Product item in products)
{
<tr>
<th>@item.Name</th>
<th>@item.Amount</th>
<th>@GetUnit(item.UnitID).Result</th>
<th>@item.PriceNetto</th>
</tr>
}
async Task<string> GetUnit(Guid id)
{
string a = "https://localhost:5001/api/Units/";
a += id.ToString();
var temp = await Http.GetJsonAsync<Unit>(a); //it fails here
return temp.Name;
}
In short I have a list of products and items on the list have "UnitID" property which I use to make a GET request. When I put anywhere in code .Result
after my async function result Visual Studio's debugger just skip the line responsible for calling the API and 'bricks' whole app without any error nor exception. Then I have to restart the project.
I tried to create second function only for returning GetUnit(id).Result
but it gave nothing. I tried to return whole Unit object and then in the table GetUnit(item.UnitID).Name
but it was just representing object (I guess...). I seems like all I need is do it with .Result
but when I do it doesn't work.
My API is made with .Net Core 2.2 and my client is made with .Net Core 3.0 (Blazor template). Is this a bug or I just can't do it that way? Thanks.
IMO, you can't do that way.In blazor,you could get all data in OnInitializedAsync
instead.Store all Name
in a string List and display the list data in view based index.For example:
@code {
private List<string> listItems = new List<string>();
protected override async Task OnInitializedAsync()
{
//get products
foreach (var product in products)
{
string a = "https://localhost:5001/api/Units/";
a += product.UnitID.ToString();
var temp = await Http.GetJsonAsync<Unit>(a);
listItems.Add(temp.Name);
}
}
}
Razor
@{ int i = 0;}
@foreach(Product item in products)
{
<tr>
<th>@item.Name</th>
<th>@item.Amount</th>
<th> @listItems[i] </th>
<th>@item.PriceNetto</th>
</tr>
i++;
}