我有一个问题,我整晚都在努力解决,我对此感到头疼,很抱歉,如果这很愚蠢,我是一个相对较新的程序员。。
它应该通过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:值不能为null。(参数"源")
System.Linq.SthrowHelper.ThrowArgumentNullException(ExceptionArgument参数)System.Linq.Enumerable.Count(IEnumerable源,函数谓词)c__DisplayClass32_0.b_1(渲染树生成器__builder3)Microsoft.AspNetCore.Components.Rendering。RenderTreeBuilder.AddContent(int序列,RenderFragment片段)Blazorise.TableRowCell.BuilderRenderTree(RenderTreeBuilder_builder)Microsoft.AspNetCore.Components.ComponentBase.<。ctor>b_6_0(渲染树生成器生成器)Microsoft.AspNetCore.Components.Rendering。ComponentState.RenderIntoBatch(RenderBatchBuilder批处理生成器,RenderFragment RenderFragment)Microsoft.AspNetCore.Components.RenderTree.RRenderInExistingBatch(RenderQueueEntry RenderQueueEntry)Microsoft.AspNetCore.Components.RenderTree.RRenderer.ProcessRenderQueue()Microsoft.AspNetCore.Components.Rendering。HtmlRenderer.HandleException(异常异常)Microsoft.AspNetCore.Components.RenderTree.RRenderer.ProcessRenderQueue()Microsoft.AspNetCore.Components.RenderTree.RRenderer.ProcessPendingRender()Microsoft.AspNetCore.Components.RenderTree.RRenderer.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.RRenderer.AddToPendingTasks(任务任务)Microsoft.AspNetCore.Components.Rendering。ComponentState.SetDirectParameters(ParameterView参数)Microsoft.AspNetCore.Components.RenderTree.RenderRootComponentAsync(int componentId,ParameterView initialParameters)Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(类型componentType,ParameterView initialParameters)Microsoft.AspNetCore.Components.Rendering。HtmlRenderer.RenderComponentAsync(类型componentType,ParameterView initialParameters)Microsoft.AspNetCore.Components.Rendering。RendererSynchronizationContext+<>c_ 11+<b__11_0>d.移动下一个()Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView参数,HttpContext HttpContext,Type componentType)Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext上下文,ServerComponentInvocationSequence调用Id,类型,ParameterView参数集合)Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext ViewContext,Type componentType,RenderMode RenderMode,对象参数)Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext上下文,TagHelperOutput输出)Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.g_Waited|0_0(任务任务,TagHelperExecutionContext executionContext,int i,int count)Revvi.Pages.Pages_Host.b_14_1()在_Host.cshtml中+Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()_Host.cshtml中的Revvi.Pages.Pages__Host.ExecuteAsync()+Layout=null;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视图上下文,字符串内容类型,可为空的状态代码)Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext视图上下文,字符串内容类型,可为空的状态代码)Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_Await|29_0(ResourceInvoker调用程序,Task lastTask,State next,Scope Scope,object State,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_Await|24_0(ResourceInvoker调用程序,Task lastTask,State next,Scope Scope,object State,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_Await|17_0(资源调用程序调用程序,任务任务,IDisposable作用域)Microsoft.AspNetCore.Routing.EndpointMiddleware.g_AwaitRequestTask|6_0(端点,任务请求任务,ILogger记录器)Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.IInvoke(HttpContext上下文)
我完全不知道该怎么办。
您的List<Fornecedor> dataModels;
最初是null
。
要么将其初始化为空列表,
List<Fornecedor> dataModels = new List<Fornecedor> ();
或者将大部分剃刀代码封装在@if (dataModels != null) { ... }
中。例如,请查看FetchData模板页面。
Blazorise.DataGrid可能知道如何处理null
集合,我希望它知道。但在"Cidade"列的Filter中也有foreach()循环,看起来这是在抛出异常。