简体   繁体   中英

Optional Model Properties Binding in .NET Core MVC

I have created one AccountModel which has following properties

public class AccountModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [StringLength(10, MinimumLength = 6)]
    public string Password { get; set; }

    [NotMapped] // Does not effect with your database
    [Compare("Password")]
    [BindRequired]
    public string ConfirmPassword { get; set; }
}

I am trying to use same model for SignUp and SignIn . This model is perfectly working for signup but when I am using same model for SignIn my model becomes Invalid.

I know the reason because, I am not passing value for Confirm Password property. I tried following

  1. I made NULLABLE by using "?" bu it is giving me warning (See attached screenshot) 在此处输入图像描述

  2. I have also tried [BindRequired] annotation which is also not working.

I am using ASP.NET Core 3.1 and trying to use single Model for both login and signup.

Is there any solution for that? I am learning .NET Core & MVC so having less knowledge about this subject.

Help is appreciated in advance.

This is called Nullable contexts , based on its documentation :

Nullable contexts enable fine-grained control for how the compiler interprets reference type variables. The nullable annotation context of any given source line is either enabled or disabled. You can think of the pre-C# 8.0 compiler as compiling all your code in a disabled nullable context: any reference type may be null. The nullable warnings context may also be enabled or disabled. The nullable warnings context specifies the warnings generated by the compiler using its flow analysis.

You can get rid of this warning like this:

#nullable enable
    public string? ConfirmPassword { get; set; }
#nullable disable

As another workaround, if you want to always get rid of this warning in your project, you can add the Nullable element in your .csproj file. Right click on your project and click "Edit Project File", then add the Nullable element to your PropertyGroup section, just like the following:

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <Nullable>enable</Nullable>
</PropertyGroup>

You just need to Re-Build your project once to see the result.

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