Emb*_*uck 12 .net c# asp.net blazor blazor-server-side
我正在开发一个服务器端 Blazor 应用程序,它使用 EntityFramework-Core 创建数据库(代码优先)。我想在 EditForm 组件中使用其中一个模型,但每当我打开包含 EditForm 组件的页面时,它都会在 _Host.cshtml 上引发 NullReferenceException。其他页面工作完全正常! Rider 屏幕截图中的错误 这是页面上给出的错误:
An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
WebApplication.Pages.Components.Customer.EditCustomer.<BuildRenderTree>b__0_4(RenderTreeBuilder __builder3)
Stack Query Cookies Headers Routing
NullReferenceException: Object reference not set to an instance of an object.
WebApplication.Pages.Components.Customer.EditCustomer.<BuildRenderTree>b__0_4(RenderTreeBuilder __builder3)
Microsoft.AspNetCore.Components.CascadingValue<TValue>.Render(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.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)
WebApplication.Pages.Pages__Host.<ExecuteAsync>b__14_1() in _Host.cshtml
<component type="typeof(App)" render-mode="ServerPrerendered"/>
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
WebApplication.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.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Show raw exception details
Run Code Online (Sandbox Code Playgroud)
这是我的 EditCustomer-Razor 组件:
@page "/customers/edit/"
@page "/customers/edit/{CustomerId:int}"
@using DataModels.Invoice
@inject IToastService _toastService
<AuthorizeView Context="authContext">
<Authorized>
<h3>Edit Customer</h3>
<EditForm OnValidSubmit="@OnValid_Submit" Context="formContext" Model="@CurrentModel">
<DataAnnotationsValidator/>
<ValidationSummary/>
<div class="form-group">
<label for="CompanyName">Company Name:</label>
<input id="CompanyName" class="form-control" type="text"/>
</div>
<div class="form-row">
<div class="form-group col-md-1">
<label for="FormOfAddress">Form:</label>
<select id="FormOfAddress" class="form-control">
<option value="1">Herr</option>
<option value="2">Frau</option>
<option value="3">Divers</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="PreName">Prename:</label>
<input id="PreName" class="form-control" type="text"/>
</div>
<div class="form-group col-md-3">
<label for="SurName">Surname:</label>
<input id="SurName" class="form-control" type="text"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="Email">Email:</label>
<input id="Email" class="form-control" type="email"/>
</div>
<div class="form-group col-md-3">
<label for="Telephone">Telephone:</label>
<input id="Telephone" class="form-control" type="tel"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="Address">Address:</label>
<input id="Address"
@bind="CurrentModel.Address.StreetName"
class="form-control"
type="text"/>
</div>
<div class="form-group col-md-1">
<label for="HouseNumber">Nr:</label>
<input id="HouseNumber"
@bind="CurrentModel.Address.HouseNumber"
class="form-control"
type="text"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-2">
<label for="ZipCode">Zip-Code:</label>
<input id="ZipCode"
@bind="CurrentModel.Address.City.ZipCode"
class="form-control"
type="text"/>
</div>
<div class="form-group col-md-3">
<label for="City">City:</label>
<input id="City"
@bind="CurrentModel.Address.City.Name"
class="form-control"
type="text"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="UstId">Ust.Id.:</label>
<input id="UstId" class="form-control" type="text"/>
</div>
<div class="form-group col-md-3">
<label for="CommercialRegisterNr">Commercial Register Nr.:</label>
<input id="CommercialRegisterNr" class="form-control" type="text"/>
</div>
</div>
<div class="form-group">
<h4>Fields</h4>
<table class="table">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</EditForm>
</Authorized>
<NotAuthorized>
<NotPermitted/>
</NotAuthorized>
</AuthorizeView>
Run Code Online (Sandbox Code Playgroud)
C#代码:
@code {
[Parameter]
public int? CustomerId { get; set; }
private Customer CurrentModel { get; set; } = new();
private List<Tuple<string, string>> Fields { get; set; }
private string TupleKey { get; set; }
private string TupleValue { get; set; }
protected override void OnInitialized()
{
Fields = new List<Tuple<string, string>>();
if (CustomerId is not null)
{
//Load from DbContext
return;
}
CurrentModel = new Customer();
}
private void OnValid_Submit(EditContext context)
{
Console.WriteLine("works.");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的客户模型:
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataModels.Invoice
{
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string CompanyName { get; set; }
public ContactPerson ContactPerson { get; set; }
public Address Address { get; set; }
public string UstId { get; set; }
public string CommercialRegisterNr { get; set; }
public IEnumerable<CustomerInfoField>? AdditionalFields { get; set; }
public IEnumerable<Invoice>? Invoices { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
当使用 @bind 抛出一个只有一两个属性的“虚拟”类时,该页面会起作用。非常感谢你的帮助,因为它让我发疯......
CBB*_*ike 29
发现如果您有两个具有相同 @page 指令的 .razor 文件,则会出现此错误。
如果异常能够告诉我这个错误,那就太好了。
就我而言,我复制了一个剃刀页面,但忘记更改文件的第一行:
@page "/databaseoracle"
Run Code Online (Sandbox Code Playgroud)
所以我有两个同名的 @page 命令。
一旦我将重复文件更改为
@page "/databaseteradata"
Run Code Online (Sandbox Code Playgroud)
错误消失了。
那是我一生中无法挽回的四个小时。希望有人会发现这很有用。
我的损失是您的收益。
发现 @page 指令的另一个问题导致 NullReferenceException:
我的看起来像这样:
@page "/mypage/{id:string}"
Run Code Online (Sandbox Code Playgroud)
或者
@page "/mypage/{id:string?}"
Run Code Online (Sandbox Code Playgroud)
更改为
@page "/mypage/{id}"
Run Code Online (Sandbox Code Playgroud)
解决了问题
我有点找到了这种行为的原因。当绑定为空时,客户类中包含的对象(即联系人)似乎为空。当使用 DbContext 使用 .Include-Calls 获取现有对象时,页面有效。这是我现在的解决方法:
protected override async Task OnInitializedAsync()
{
Fields = new List<Tuple<string, string>>();
if (CustomerId is not null)
{
await using var context = new ApplicationDbContext();
CurrentModel = await context.Customers
.Include(x => x.ContactPerson)
.Include(x => x.Address)
.Include(x => x.AdditionalFields)
.FirstOrDefaultAsync(c => c.Id == CustomerId);
return;
}
CurrentModel = Customer.CreateEmpty();
}
Run Code Online (Sandbox Code Playgroud)
以及新对象的静态方法:
public static Customer CreateEmpty()
{
var customer = new Customer
{
ContactPerson = new ContactPerson()
};
var address = new Address
{
City = new City()
};
customer.Address = address;
customer.AdditionalFields = new List<CustomerInfoField>();
return customer;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11394 次 |
最近记录: |