简体   繁体   中英

Disable [Required] attribute base on condition in ASP.NET Core and Entity Framework Core

I have a table UserApplication which has more than 100 columns. The model class for it looks like this:

public class UserApplication
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name{ get; set; }
    [Required]
    public string LastName{ get; set; }
    public string Address{ get; set; }
    ....
    ....
    .....  
    // so on ....
}

I have break these column data section-wise into multiple pages (razor pages asp.net core 3.1). So roughly I have 10 pages, each having 10 column values respectively, some has required attribute

Now on page load I get an error

SqlNullValueException: Data is Null. This method or property cannot be called on Null values

This error occurs because of null values for required columns (on another pages).

Is there any way I can disable the [Required] attribute on page load? And later enable it when user post the page and show required validation message.

Error screenshot:

在此处输入图像描述

I believe you also get this error when you have not built and run your update scripts on the database, so your DB doesn't actually have the columns it needs.

Just to double check, have you created the migrations for these columns, and applied them to your Database?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM