值不能为空。参数名称:尝试通过网络获取数据时的来源api

Value cannot be null. Parameter name: source when trying to get data with web api

我有一个问题,我整晚都在努力解决这个问题,我正在为此绞尽脑汁,抱歉,如果它很愚蠢,我是一个相对较新的程序员..

它应该通过 Web API 从我的数据库中获取一些数据,并将其显示在数据网格中(使用 blazorise 的数据网格),但它不起作用..

代码:

@using Newtonsoft.Json; 
@page "/email/inbox"
<Row>
    <Column>
        <Card Margin="Margin.Is4.OnY">
            <CardHeader>
                <CardTitle>Data Grid</CardTitle>
            </CardHeader>
            <CardBody>
                <CardText>Combine diferent datagrid options</CardText>
            </CardBody>
            <CardBody>
                <DataGrid TItem="Fornecedor"
                          Data="@dataModels"
                          EditMode="DataGridEditMode.Popup"
                          Editable="true"
                          Sortable="true"
                          Filterable="true"
                          ShowPager="true"
                          RowInserted="@OnRowInserted"
                          RowUpdated="@OnRowUpdated"
                          RowRemoved="@OnRowRemoved"
                          UseInternalEditing="true"
                          @bind-SelectedRow="@fornecedorSelecionado"
                          Striped="true"
                          Bordered="true"
                          Hoverable="true"
                          CustomFilter="@OnCustomFilter">
                    <DataGridAggregates>
                        <DataGridAggregate TItem="Fornecedor" Field="@nameof( Fornecedor.Email )" Aggregate="DataGridAggregateType.Count">
                            <DisplayTemplate>
                                @($"Total emails: {context.Value}")
                            </DisplayTemplate>
                        </DataGridAggregate>
                        <DataGridAggregate TItem="Fornecedor" Field="@nameof( Fornecedor.Validado )" Aggregate="DataGridAggregateType.TrueCount" />
                    </DataGridAggregates>
                    <DataGridColumns>
                        <DataGridCommandColumn TItem="Fornecedor" Width="170px">
                            <NewCommandTemplate>
                                <Button Color="Color.Success" Clicked="@context.Clicked">New</Button>
                            </NewCommandTemplate>
                            <EditCommandTemplate>
                                <Button Color="Color.Primary" Clicked="@context.Clicked">Edit</Button>
                            </EditCommandTemplate>
                            <SaveCommandTemplate>
                                <Button Color="Color.Primary" Clicked="@context.Clicked">Save</Button>
                            </SaveCommandTemplate>
                            <DeleteCommandTemplate>
                                <Button Color="Color.Danger" Clicked="@context.Clicked">Delete</Button>
                            </DeleteCommandTemplate>
                            <CancelCommandTemplate>
                                <Button Color="Color.Secondary" Clicked="@context.Clicked">Cancel</Button>
                            </CancelCommandTemplate>
                            <ClearFilterCommandTemplate>
                                <Button Color="Color.Warning" Clicked="@context.Clicked">Clear Filter</Button>
                            </ClearFilterCommandTemplate>
                        </DataGridCommandColumn>
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.Id )" Caption="#" Sortable="false" Width="60px" />
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.NomeEmpresa )" Caption="Fornecedor" Editable="true">
                            <FilterTemplate>
                                <TextEdit Placeholder="Search name" TextChanged="@(v=>context.TriggerFilterChange(v))" />
                            </FilterTemplate>
                        </DataGridColumn>
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.NomeContato )" Caption="Contato" Editable="true" />
                        <DataGridDateColumn TItem="Fornecedor" Field="@nameof( Fornecedor.Telefone )" DisplayFormat="{(00)00000-0000}" Caption="Telefone" Editable="true" />
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.Email )" Caption="Email" Editable="true" />
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.CEP )" Caption="CEP" Editable="true" />
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.Cidade )" Caption="Cidade" Editable="true">
                            <FilterTemplate>
                                <Select TValue="string" SelectedValueChanged="@(e => context.TriggerFilterChange(e == "*" ? "" : e.ToString()))">
                                    <SelectItem Value="@("*")">All</SelectItem>
                                    @foreach (var item in dataModels)
                                    {
                                        <SelectItem Value="@item.Cidade">@item.Cidade</SelectItem>
                                    }
                                </Select>
                            </FilterTemplate>
                        </DataGridColumn>
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.Endereco )" Caption="Endereço" Editable="true" Filterable="false" />
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.Servico )" Caption="Serviço" Editable="true" />
                        <DataGridColumn TItem="Fornecedor" Field="@nameof( Fornecedor.Especialidade )" Caption="Especialidades" Editable="true" />
                        <DataGridCheckColumn TItem="Fornecedor" Field="@nameof(Fornecedor.Validado)" Caption="Validado" Editable="true" Filterable="false">
                            <DisplayTemplate>
                                <Check TValue="bool?" Checked="context.Validado" Disabled="true" ReadOnly="true" />
                            </DisplayTemplate>
                        </DataGridCheckColumn>
                    </DataGridColumns>
                </DataGrid>
            </CardBody>
        </Card>
    </Column>
</Row>
<Row>
    <Column>
        <Card>
            <CardHeader>
                <CardTitle>Fornecedor Selecionado</CardTitle>
            </CardHeader>
            <CardBody>
                <Fields>
                    <Field>
                        <FieldLabel>Fornecedor</FieldLabel>
                        <FieldBody>
                            <TextEdit ReadOnly="true" Text="@fornecedorSelecionado?.NomeEmpresa"></TextEdit>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>Contato</FieldLabel>
                        <TextEdit ReadOnly="true" Text="@fornecedorSelecionado?.NomeContato"></TextEdit>
                    </Field>
                </Fields>
                <Fields>
                    <Field>
                        <FieldLabel>Telefone</FieldLabel>
                        <FieldBody>
                            <NumericEdit TValue="int" ReadOnly="true" Text="@fornecedorSelecionado?.Telefone"></NumericEdit>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>Email</FieldLabel>
                        <TextEdit ReadOnly="true" Text="@fornecedorSelecionado?.Email"></TextEdit>
                    </Field>
                </Fields>
            </CardBody>
        </Card>
    </Column>
</Row>
@code{
    public class DataService
    {
        HttpClient client = new HttpClient();

        public async Task<List<Fornecedor>> GetUsuariosAsync()
        {
            try
            {
                string url = "https://myAPI.azurewebsites.net/Api/Fornecedores";
                var response = await client.GetStringAsync(url);
                var fornecedores = JsonConvert.DeserializeObject<List<Fornecedor>>(response);
                return fornecedores;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    DataGridEditMode editMode = DataGridEditMode.Popup;

    bool editable = true;
    bool sortable = true;
    bool filterable = true;
    bool showPager = true;

    Fornecedor fornecedorSelecionado;

    public class Fornecedor
    {
        public int Id { get; set; }
        public string NomeEmpresa { get; set; }
        public string NomeContato { get; set; }
        public int Telefone { get; set; }
        public string Email { get; set; }
        public int CEP { get; set; }
        public string Cidade { get; set; }
        public string Endereco { get; set; }
        public string Servico { get; set; }
        public string Especialidade { get; set; }
        public string Especialidade_dois { get; set; }
        public string Especialidade_tres { get; set; }
        public string Website { get; set; }
        public bool? Validado { get; set; }
    }

    DataService dataService;

    protected async Task FornecedoresAPI()
    {
        try
        {
            await dataService.GetUsuariosAsync();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    List<Fornecedor> dataModels;
    // generated with https://mockaroo.com/
    protected override async Task OnInitializedAsync()
    {
        dataService = new DataService();
        dataModels = await dataService.GetUsuariosAsync();

    }

    string customFilterValue;

    bool OnCustomFilter(Fornecedor model)
    {
        if (string.IsNullOrEmpty(customFilterValue))
            return true;

        return
            model.NomeEmpresa?.Contains(customFilterValue, StringComparison.OrdinalIgnoreCase) == true
            || model.NomeContato?.Contains(customFilterValue, StringComparison.OrdinalIgnoreCase) == true
            || model.Email?.Contains(customFilterValue, StringComparison.OrdinalIgnoreCase) == true;
    }
} 

我收到这个错误:

ArgumentNullException: Value cannot be null. (Parameter 'source')

System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument) System.Linq.Enumerable.Count(IEnumerable source, Func predicate)
Blazorise.DataGrid._DataGridAggregateRow.CountOf(DataGridColumn column)
Blazorise.DataGrid._DataGridAggregateRow.Calculate(DataGridAggregate column)
Blazorise.DataGrid._DataGridAggregateRow+<>c__DisplayClass32_0.b__1(RenderTreeBuilder __builder3) Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.AddContent(int sequence, RenderFragment fragment) Blazorise.TableRowCell.BuildRenderTree(RenderTreeBuilder __builder) Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder) Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment) Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry) Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue() Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception) Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue() Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessPendingRender() Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(int componentId, RenderFragment renderFragment) Microsoft.AspNetCore.Components.RenderHandle.Render(RenderFragment renderFragment) Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged() Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync() Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync() Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception) Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(Task task) Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters) Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters) Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters) Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters) Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c__11+<b__11_0>d.MoveNext() Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType) Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection) Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, object parameters) Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count) Revvi.Pages.Pages__Host.b__14_1() in _Host.cshtml + Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync() Revvi.Pages.Pages__Host.ExecuteAsync() in _Host.cshtml + Layout = null; Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

而且我完全不知道该怎么做..

您的List<Fornecedor> dataModels;最初是null

要么初始化为空列表,

List<Fornecedor> dataModels = new List<Fornecedor> ();

或者将大部分剃须刀代码包装在 @if (dataModels != null) { ... }
中 查看 FetchData 模板页面的示例。

可能 Blazorise.DataGrid 确实知道如何处理 null 集合,我希望它能。但是您在 "Cidade" 列的 Filter 中也有 foreach() 循环,看起来这是抛出异常。