是否可以在表行中添加异步函数结果?

我正在为我的REST API创建Web客户端,我想在表中添加一个包含异步功能结果的字段。

@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模板)构成。这是一个错误还是我不能那样做?谢谢。

d4133456929295 回答:是否可以在表行中添加异步函数结果?

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

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

IMO,您不能那样做。在blazor中,您可以将所有数据存储在<%= f.check_box :acc_type,id: "id_check_box" %> <%= f.date_select :expire_date,{ discard_day: true,start_year: Date.today.year,end_year: (Date.today.year + 10),required: true },class: 'form-control',id: "id_expire_date" %> <script> $('#id_check_box').click(function() { if (this.checked) { $('select#id_expire_date').attr('disabled','disabled'); } else { $('select#id_expire_date').removeAttr('disabled'); } }); </script> 中。将所有OnInitializedAsync存储在字符串List中并在基于视图的索引中显示列表数据。例如:

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);
        }
    }
}
本文链接:https://www.f2er.com/3169385.html

大家都在问