【问题标题】:Blazor Unhandled exception rendering componentBlazor 未处理的异常呈现组件
【发布时间】:2021-01-27 04:30:59
【问题描述】:

我是 Blazor 的初学者,正在制作一个简单的待办事项列表项目。添加列表时出现错误。 未处理的异常渲染组件:对象引用未设置为对象的实例。

System.NullReferenceException: Object reference not set to an instance of an object.
   at FrontEnd.Pages.Index.AddList(KeyboardEventArgs e) in C:\Users\bryan\source\repos\Productivity_App\FrontEnd\Pages\Index.razor.cs:line 20
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

我尝试搜索问题并找到了类似的帖子here,但答案对我没有帮助,看着问题。我认为修复它与 blazor 生命周期有关。这是与错误相关的代码。
Index.razor

    <div class="toDoList">
        @if (ToDoListCollection != null)
        {
            @foreach (string toDoList in ToDoListCollection)
            {
                <input type="checkbox" id="checkbox">
                <label for="checkbox">@toDoList</label>
                <hr />
            }
        }
        else
        {}
    </div>

Index.razor.cs

namespace FrontEnd.Pages
{
    public partial class Index
    {
        public bool IsCompleted { get; set; }
        public string Description { get; set; }
        public List<string> ToDoListCollection { get; set; }

        public void AddList(KeyboardEventArgs e)
        {
            if (e.Key == "Enter" && !string.IsNullOrWhiteSpace(Description) || 
                e.Key == "NumpadEnter" && !string.IsNullOrWhiteSpace(Description))
            {
                ToDoListCollection.Add($"{Description}"); // This is the line that the error message is referencing 
                Description = null;
            } else
            {}
        }

【问题讨论】:

  • 集合初始化了吗?在您提供的代码中,我没有看到任何类似于 ToDoListCollection = new List&lt;string&gt;() 的内容

标签: c# blazor blazor-webassembly


【解决方案1】:

我假设您的 ToDoListCollection 具有 null 值,因为它没有被初始化。

为您的集合分配一个默认值。

public List<string> ToDoListCollection { get; set; } = new List<string>();

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 2020-11-04
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2021-04-21
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多