C#のBlazorでforeachを使用すると、
An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
BlazorApp1.Pages.Article001.BuildRenderTree(RenderTreeBuilder __builder) in Article001.razor, line 20
この様なエラーメッセージが表示されてしまいます。
目的としましては、インスタンスに記入したオブジェクトを<ul><li>に自動で押込んでくれる様に(ここまでは出来ました)、
かつそれらを降順やランダムなどの並び替えもできるようになりたいです。(今回はこちらで困っております・・・)
以下エラー文の詳細になります。
NullReferenceException: Object reference not set to an instance of an object. BlazorApp1.Pages.Article001.BuildRenderTree(RenderTreeBuilder __builder) in Article001.razor - </li> } </ul>*@ <ul> @foreach (var sorts in sorts) { <li class="builds"> <a href="@sorts.HtmlUrl"> <img src="/Images/Builds/@sorts.Name" style="width:100px; height:auto; border:5px #ff0000 solid; margin:10px;" /> <span>@sorts.Number @sorts.Description</span> 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.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) BlazorApp1.Pages.Pages__Host.<ExecuteAsync>b__14_1() in _Host.cshtml - <base href="~/" /> <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" /> <link href="css/site.css" rel="stylesheet" /> </head> <body> <app> <component type="typeof(App)" render-mode="ServerPrerendered" /> </app> <div id="blazor-error-ui"> <environment include="Staging,Production"> An error has occurred. This application may no longer respond until reloaded. </environment> Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync() BlazorApp1.Pages.Pages__Host.ExecuteAsync() in _Host.cshtml - @page "/" @namespace BlazorApp1.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @{ Layout = null; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> 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)
以下がコードになります。
Blazor
1 2@page "/article001" 3 4<h3>Article001</h3> 5 6//foreachで自動で列挙する(ここまでは苦戦しながらもできました。) 7<ul> 8 @foreach (var build in builds) 9 { 10 <li class="builds"> 11 <a href="@build.HtmlUrl"> 12 <img src="/Images/Builds/@build.Name" style="width:100px; height:auto; 13 border:5px #ff0000 solid; margin:10px;" /> 14 <span>@build.Number @build.Description</span> 15 </a> 16 </li> 17 } 18</ul> 19 20//foreachでsortしたのを並べる(これを導入した途端エラーが出る様になってしまいました。) 21<ul> 22 @foreach (var sorts in sorts) 23 { 24 <li class="builds"> 25 <a href="@sorts.HtmlUrl"> 26 <img src="/Images/Builds/@sorts.Name" style="width:100px; height:auto; 27 border:5px #ff0000 solid; margin:10px;" /> 28 <span>@sorts.Number @sorts.Description</span> 29 </a> 30 </li> 31 } 32</ul> 33 34<button class="btn btn-primary" @onclick="SortItems">Sort me</button> 35 36@code { 37 38 public class ArticleItem 39 { 40 public int Number { get; set; } 41 public string Name { get; set; } 42 public string Description { get; set; } 43 44 public string HtmlUrl { get; set; } 45 46 public ArticleItem(int number, string name, string description, string htmlurl) 47 { 48 this.Number = number; 49 this.Name = name; 50 this.Description = description; 51 this.HtmlUrl = htmlurl; 52 } 53 } 54 55 List<ArticleItem> sorts; 56 List<ArticleItem> builds = new List<ArticleItem> 57 { 58 new ArticleItem(1, "vermeer.jpg", "フェルメールの真珠の耳飾りの少女", "none"), 59 new ArticleItem(2, "mona_lisa.jpg", "ダ・ヴィンチのモナ・リザ", "https://localhost:44391/mona_lisa"), 60 new ArticleItem(3, "unnamed.jpg", "作者不明のタイトル不明", "none"), 61 new ArticleItem(4, "the_last_supper.jpg", "ダ・ヴィンチの最後の晩餐", "none") 62 }; 63 64 void SortItems() 65 { 66 sorts = builds; 67 sorts.Sort((a, b) => string.Compare(a.Description, b.Name)); 68 } 69} 70
Listとインスタンスを使ってオブジェクトを作り
それを@foreachによって一気に列挙するというコードです。
ソート機能も付けたいと思いsorts.Sortを使ったりもしております。
@foreachの部分を削除すると問題なくページは表示されるので、この部分が原因かと思うのですが、
調べてみるとnullにすると良いとのことで、手探りで、
List<ArticleItem> results; を List<ArticleItem> results = null; にしてみたりも変化起きず。
投げっぱなしな質問になっており大変恐縮なのですが、
入門書を読み直したりしても解決できず日にちが過ぎてしまいまして・・・。
どなたか、心当たりある方いらしたら部分的にでもご教授願いますでしょうか。
どうぞ宜しくお願い申し上げます。
回答2件
あなたの回答
tips
プレビュー