Blazor双向绑定搜索栏报空引用异常,模型处理是否有误?
问题:Blazor中使用自定义模型实现搜索时触发NullReferenceException
原字符串版本可正常运行的代码
<MudTextField @bind-Value="@searchTerm" Placeholder="Sök" /> @foreach (var item in filteredItems) { <p>@item</p> } @code { private string searchTerm = ""; private List<string> items = new List<string> { "1","2","3" }; private IEnumerable<string> filteredItems => items.Where(i => i.ToLower().Contains(searchTerm.ToLower())); }
切换为Exercise模型后出现异常
控制台抛出错误:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at
修改后的Exercise模型代码
<MudTextField @bind-Value="@searchTerm" Placeholder="Sök" /> @foreach (var item in filteredItems) { <p>@item.Title</p> } @code { private string searchTerm = ""; private List<Exercise> items = new List<Exercise> { new Exercise { Id = 1, Title = "Push-ups", Instructions = new Dictionary<int, string>() { { 1, "Get into a plank position with your hands slightly wider than shoulder-width apart." }, { 2, "Lower your body until your chest nearly touches the floor." }, { 3, "Push your body back up to the starting position, keeping your elbows close to your body." } } }, new Exercise { Id = 2, Title = "Squats", Instructions = new Dictionary<int, string>() { { 1, "Stand with your feet shoulder-width apart." }, { 2, "Lower your body as if you are sitting back into a chair." }, { 3, "Keep your knees over your ankles and your weight in your heels." }, { 4, "Push back up to the starting position." } } }, new Exercise { Id = 3, } }; private IEnumerable<Exercise> filteredItems => items.Where(i => i.Title.ToLower().Contains(searchTerm.ToLower())); }
使用数据仓库时同样出错
@inject IExerciseDataStore<Exercise> exerciseDataStore ... protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); items = await exerciseDataStore.GetAllExercisesAsync(); }
原因及解决办法
直接原因:
- 手动初始化的第三个Exercise对象未赋值
Title属性,该属性为null,调用i.Title.ToLower()时触发空引用异常。 - 使用数据仓库时,返回的集合中可能存在
Title为null的Exercise实例,同样会引发该异常。
- 手动初始化的第三个Exercise对象未赋值
解决方式:
- 初始化Exercise对象时确保
Title不为空,比如给第三个对象设置Title = "未命名训练"。 - 在过滤逻辑中增加空值判断,避免对
null调用方法:private IEnumerable<Exercise> filteredItems => items.Where(i => !string.IsNullOrEmpty(i.Title) && i.Title.ToLower().Contains(searchTerm.ToLower())); - 使用数据仓库时,要么确保返回的所有Exercise的
Title都已正确赋值,要么同样在过滤条件中加入空值检查。
- 初始化Exercise对象时确保
内容的提问来源于stack exchange,提问作者LordAhune
相关产品推荐
相关产品推荐

