首页 > 解决方案 > Register.razor 中的错误:System.NullReferenceException:“对象引用未设置为对象的实例。”

问题描述

我正在 Blazor (C#) 服务器端做一个应用程序。我在 Register.razor 文件中收到以下错误: System.NullReferenceException: 'Object reference not set to an instance of an object。<> 4__this._dataContext 为空。我还收到以下警告:字段 Register._dataContext 从未分配给,并且始终具有其默认值 null。当我想将注册数据保存到数据库时(单击“注册”按钮),此错误发生在我身上。

我究竟做错了什么?

注册剃须刀:

@page "/register"

@using TestBlazor.Models
@using TestBlazor.Data

@*@inject IToDoListService user*@

<br />
<br />

<h3><b>Register</b></h3>
<br />

<EditForm class="needs-validation" Model="@_user" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit">
    <div class="alert @StatusClass">@StatusMessage</div>
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div class="form-group">
        <p><b>User name</b></p>
        <input id="username" class="solid" name="username" placeholder="Your username.." @bind-value="_user.UserName" />
        <ValidationMessage For="@(() => @_user.UserName)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p><b>Password</b></p>
        <input type="password" class="solid" id="password" placeholder="Your password.." @bind-value="_user.Password" />
        <ValidationMessage For="@(() => @_user.Password)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p><b>Email</b></p>
        <input id="email" class="solid" placeholder="you@example.com" @bind-value="_user.Email" />
        <ValidationMessage For="@(() => @_user.Email)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p><b>Company</b></p>
        <input id="company" class="solid" placeholder="Your company.." @bind-value="_user.Company" />
        <ValidationMessage For="@(() => @_user.Company)"></ValidationMessage>
    </div>


    <br />

    <button disabled="@loading" class="btn btn-primary" onclick="AddUser">

        @if (loading)
        {
            <span class="spinner-border spinner-border-sm mr-1"></span>
            <NavLink href="/login" class="btn btn-link">Register</NavLink>
        }
        Register
    </button>
    <NavLink href="/login" class="btn btn-link">Login</NavLink>
</EditForm>



@code {
    private User _user = new User();

    private string StatusMessage;
    private string StatusClass;

    private bool loading;
    private readonly AppDbContext _dataContext; //warning this record: Field Register._dataContext is never assigned to, and will always have its default value null.

    //provjeriti: var context = new SchoolContext()


    private void OnValidSubmit()
    {
        if (loading == true)
        {
            Console.WriteLine("You have successfully registered!");
        }

        else
        {
            loading = false;
            Console.WriteLine("Check your information again!");
        }
    }

    //protected void HandleValidSubmit()
    //{
    //    StatusClass = "alert-info";
    //    StatusMessage = " You have successfully registered! Please click the Login button to log in!";

@*}*@


private async void HandleValidSubmit()
{
    try
    {
        _dataContext.User.Add(_user); //error in this record System.NullReferenceException: 'Object reference not set to an instance of an object.' <> 4__this._dataContext was null.

        await _dataContext.SaveChangesAsync();
    }
    catch
    {
        base.StateHasChanged();
    }
    _user = new User();
    base.StateHasChanged();
}


protected void HandleInvalidSubmit()
{
    StatusClass = "alert-danger";
    StatusMessage = " Check your information again!";
}


//public bool doesCompanyExist(string Company)
//{
//    User u = new User();
//    if (u.IsValid(Company))
//        return true;
//    else
//        return false;

//}

}

用户.cs:

using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TestBlazor.Data;

namespace TestBlazor.Models
{
    [Table("Users")]
    public class User

    {

        [Display(AutoGenerateField = false)]
        public int UserId { get; set; }

        [Display(Name = "UserName")]
        [Required(ErrorMessage = "UserName is required.")]
        public string UserName { get; set; }

        [Display(Name = "Password")]
        [Required]
        [MinLength(8, ErrorMessage = "password must be atleast 8 characters")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Email")]
        [Required(ErrorMessage = "Email is required.")]
        public string Email { get; set; }

        [Display(Name = "Company")]
        [StringLength(255)]
        [Required(ErrorMessage = "Company is required.")]
        [Remote("doesCompanyExist", "Company", HttpMethod = "POST", ErrorMessage = "Company already exists. Please enter a different company.")]
        public string Company { get; set; }

        public User GetRegisteredUser()
        {
            return new User
            {
                UserName = UserName,
                Password = Password,
                Email = Email,
                Company = Company,

            };
        }

    }

}

AppDbContext.cs:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestBlazor.Models;

namespace TestBlazor.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext()
        {

        }

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=testblazor;Integrated Security=True;");
            }
        }

        //protected override void OnModelCreating(ModelBuilder modelBuilder)
        //{
        //    base.OnModelCreating(modelBuilder);
        //    modelBuilder.Entity<User>()
        //}

        public DbSet<User> User { get; set; }
        public DbSet<Item> Items { get; set; }


    }

}

标签: c#htmlcssblazor

解决方案


推荐阅读