Optional Model Properties Binding in .NET Core MVC

六眼飞鱼酱① 提交于 2021-02-18 08:42:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/61436203/optional-model-properties-binding-in-net-core-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!