2
votes

I have this issue that I've been trying to solve the whole night and I'm cracking my head over this, sorry if it's silly, I'm a relatively new programmer..

It is supposed to get some data from my database via a Web API, and show it in a data grid (using blazorise's datagrid) but it just doesn't work..

Code:

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

I get this error:

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)

And I have absolutely no idea of what to do..

1
Did you ensure your dataModels data source is not null and does not contain any null record?VRoxa
As I can see, you are fetching your dataModels async. Ensure you are not rendering nothing related with this dataModels right before you completely fetch it. It is just null until the Task<> completes.VRoxa

1 Answers

3
votes

Your List<Fornecedor> dataModels; is initially null.

Either initialize it to an empty list,

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.

It could be that the Blazorise.DataGrid does know how to handle a null collection, I would expect it to. But you also have foreach() loop in the Filter of the "Cidade" column, it looks like that is throwing the exception.