【问题标题】:Is this possible to add async function result into table row?这可以将异步函数结果添加到表行中吗?
【发布时间】:2019-11-04 02:27:32
【问题描述】:

我正在为我的 REST API 创建网络客户端,并且我想在我的表中添加一个包含异步函数结果的字段。

@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;
}

简而言之,我有一个产品列表,列表中的项目具有“UnitID”属性,我用它来发出 GET 请求。当我在我的异步函数结果之后将代码.Result 放在任何地方时,Visual Studio 的调试器只需跳过负责调用 API 和“砖块”整个应用程序的行,没有任何错误或异常。然后我必须重新启动项目。

我试图创建第二个函数仅用于返回GetUnit(id).Result,但它什么也没提供。我试图返回整个 Unit 对象,然后在表中 GetUnit(item.UnitID).Name 但它只是代表对象(我猜......)。我似乎只需要使用.Result 来完成它,但是当我这样做时它不起作用。

我的 API 是用 .Net Core 2.2 制作的,我的客户端是用 .Net Core 3.0(Blazor 模板)制作的。这是一个错误还是我不能那样做?谢谢。

【问题讨论】:

  • 您可以在表格中等待您的方法而不是使用 .Result 吗?喜欢&lt;th&gt;@(await GetUnit(item.UnitID))&lt;/th&gt;
  • 我不明白你的问题。

标签: c# asp.net-core blazor-client-side


【解决方案1】:

您不需要这样做。我建议在异步操作中调用它,如下所示:
剃刀专注于视图,控制器/模型专注于数据。

public async Task<IActionResult> SomeAction(Guid id)
{
    var products = ..;
    foreach (var item in products)
    {
        p.UnitID = await GetUnit(item.UnitID);
    }
    return View(products);
}

private 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;
}

public class Product 
{
    public string Name { get; set; }    
    public decimal Amount { get; set; } 
    public string UnitID { get; set; }  
    public string PriceNetto { get; set; }  
}

【讨论】:

    【解决方案2】:

    IMO,你不能那样做。在 blazor 中,你可以获取 OnInitializedAsync 中的所有数据。将所有 Name 存储在字符串列表中,并在基于视图的索引中显示列表数据。例如:

    @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);
            }
        }
    }
    

    剃须刀

    @{  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++;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 2021-04-09
      • 2011-12-30
      相关资源
      最近更新 更多