我写了以下代码,在传递字符串时效果很好
<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()));
}
然后我更改了代码,但通过了一个模型练习,但是那个 dosen 工作
我在控制台上给我以下错误。
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常呈现组件:对象引用未设置到对象的实例。 System.NullReferenceException:对象引用未设置到对象的实例。 在
<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()));
}
有人知道为什么吗?起初我厌倦了使用我的 IExerciseDataStore 来获取我的练习,但我一遍又一遍地遇到同样的问题。
@inject IExerciseDataStore<Exercise> exerciseDataStore
...
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
items = await exerciseDataStore.GetAllExercisesAsync();
}
使用 MudBlazor 时正确制定了 Binding,doc 阅读更多。 总之:@bind-Value="SearchTerm" 也会在“后台”绑定 ValueChanged="SearchTerm"。
我遇到的问题是@Axekan 在我不断收到 NullReferenceExccption 的评论中写的,因为加载页面时我拥有的数据为空。
...
new Exercise
{
Id = 3,
}
Title 或 Instruction 等属性未设置并且将为 null,因为 Title - string,Instructions - Dictionary 这些是引用类型,如果未设置将在模型(练习)初始化时指向 null。
改为:为了解决空引用,我加载了页面。
...
new Exercise
{
Id = 3,
Title = String.Empty,
Instructions = new Dictornary<int,string>()
}