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

Posted

技术标签:

【中文标题】值不能为空。参数名称:尝试使用 web api 获取数据时的源【英文标题】:Value cannot be null. Parameter name: source when trying to get data with web api 【发布时间】:2020-08-26 17:42:09 【问题描述】:

我有这个问题,我整晚都在尝试解决这个问题,我为此绞尽脑汁,对不起,如果这很愚蠢,我是一个相对较新的程序员..

它应该通过 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:值不能为空。 (参数'来源')

System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument 参数) System.Linq.Enumerable.Count(IEnumerable 源,Func 谓词) Blazorise.DataGrid._DataGridAggregateRow.CountOf(DataGridColumn 列) Blazorise.DataGrid._DataGridAggregateRow.Calculate(DataGridAggregate 列) Blazorise.DataGrid._DataGridAggregateRow+c__DisplayClass32_0.b__1(RenderTreeBuilder __builder3) Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.AddContent(int 序列,RenderFragment 片段) Blazorise.TableRowCell.BuildRenderTree(RenderTreeBuilder __builder) Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder 构建器) 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(异常异常) 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(异常异常) Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(任务任务) Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView 参数) Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters) Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(类型 componentType,ParameterView 初始参数) Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(类型 componentType,ParameterView 初始参数) Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+c__11+d.MoveNext() Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView参数,HttpContext httpContext,类型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 上下文,TagHelperOutput 输出) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.g__Awaited|0_0(任务任务,TagHelperExecutionContext executionContext,int i,int count) _Host.cshtml 中的 Revvi.Pages.Pages__Host.b__14_1() + Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync() _Host.cshtml 中的 Revvi.Pages.Pages__Host.ExecuteAsync() + 布局=空; Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage 页面,ViewContext 上下文) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage 页面,ViewContext 上下文,bool invokeViewStarts) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext 上下文) 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 调用者,Task lastTask,State next,Scope 范围,对象状态,bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed 上下文) 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 调用者,Task lastTask,State next,Scope 范围,对象状态,bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed 上下文) 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 调用程序,任务任务,IDisposable 范围) Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端点端点、任务 requestTask、ILogger 记录器) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

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

【问题讨论】:

您是否确保您的dataModels 数据源不为空且不包含任何空记录? 如我所见,您正在获取您的dataModels async。确保在完全获取它之前没有渲染与此 dataModels 相关的任何内容。在 Task&lt;&gt; 完成之前,它只是 null。 【参考方案1】:

您的 List&lt;Fornecedor&gt; dataModels; 最初是 null

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

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

或将大部分剃须刀代码包装在@if (dataModels != null) ... 以 FetchData 模板页面为例。

Blazorise.DataGrid 可能确实知道如何处理 null 集合,我希望它知道。但是您在“Cidade”列的过滤器中也有 foreach() 循环,看起来这会引发异常。

【讨论】:

以上是关于值不能为空。参数名称:尝试使用 web api 获取数据时的源的主要内容,如果未能解决你的问题,请参考以下文章

使用 DAL2 访问数据:值不能为空。参数名称:con

异常详细信息:System.ArgumentNullException:值不能为空。参数名称:运行时的meth

值不能为空。参数名称:元素

值不能为空。参数名称:starter中的connectionString appsettings.json

值不能为空。参数名称:routeCollection + ApiController

反序列化错误:值不能为空。参数名称:类型