值不能为空。参数名称:尝试使用Web API获取数据时的源

嗨,我遇到了一个问题,我一直在努力解决一整晚,对此我不敢恭维,如果这很傻,对不起,我是一个相对较新的程序员。 它应该通过Web api从我的数据库中获取一些数据,并将其显示在数据网格中(使用blazorise的datagrid),但这只是行不通。

码:

@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<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)
Blazorise.DataGrid._DataGridAggregateRow<TItem>.CountOf(DataGridColumn<TItem> column)
Blazorise.DataGrid._DataGridAggregateRow<TItem>.Calculate(DataGridAggregate<TItem> aggregate, DataGridColumn<TItem> column)
Blazorise.DataGrid._DataGridAggregateRow<TItem>+<>c__DisplayClass32_0.<BuildRenderTree>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<TResult>+<<InvokeAsync>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.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
Revvi.Pages.Pages__Host.<ExecuteAsync>b__14_1() in _Host.cshtml
+
        <component type="typeof(App)" render-mode="ServerPrerendered" />
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<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(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<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>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.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

而且我绝对不知道该怎么办..

评论
  • 你美
    你美 回复

    dataModels is empty at component creation, iniatize it with an empty list:

    List<Fornecedor> dataModels = new List<Fornecedor>();
    
  • 骗局
    骗局 回复

    Your List<Fornecedor> dataModels; is initially null.

    要么将其初始化为一个空列表,

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

    or wrap most of your razor code in an @if (dataModels != null) { ... }
    look at the FetchData template page for an example.