问题描述
我创建了一个具有以下属性的 AccountModel
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; }
}
我正在尝试对 SignUp
和 SignIn
使用相同的模型.这个模型非常适合注册,但是当我为 SignIn
使用相同的模型时,我的模型变得无效.
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.
我知道原因,因为我没有为 Confirm Password 属性传递值.我尝试了以下
I know the reason because, I am not passing value for Confirm Password property. I tried following
我使用?"创建了
NULLABLE
但它给了我警告(见附件截图)
I made
NULLABLE
by using "?" bu it is giving me warning (See attached screenshot)
我也试过 [BindRequired]
注释,它也不起作用.
I have also tried [BindRequired]
annotation which is also not working.
我正在使用 ASP.NET Core 3.1 并尝试使用单一模型进行登录和注册.
I am using ASP.NET Core 3.1 and trying to use single Model for both login and signup.
有什么解决办法吗?我正在学习 .NET Core &MVC 所以对这个主题的了解较少.
Is there any solution for that? I am learning .NET Core & MVC so having less knowledge about this subject.
提前感谢您的帮助.
推荐答案
这被称为 Nullable contexts,基于其 文档:
This is called Nullable contexts, based on its documentation:
可空上下文可以对编译器如何解释引用类型变量进行细粒度控制.任何给定源代码行的可为空的注释上下文要么启用要么禁用.您可以将 C# 8.0 之前的编译器视为在禁用的可为空上下文中编译所有代码:任何引用类型都可能为空.也可以启用或禁用可为空警告上下文.可为空的警告上下文指定编译器使用其流分析生成的警告.
你可以像这样摆脱这个警告:
You can get rid of this warning like this:
#nullable enable
public string? ConfirmPassword { get; set; }
#nullable disable
作为另一种解决方法,如果您想始终摆脱项目中的此警告,您可以在 .csproj
文件中添加 Nullable
元素.右键单击您的项目并单击编辑项目文件",然后将 Nullable
元素添加到您的 PropertyGroup
部分,如下所示:
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.
这篇关于.NET Core MVC 中的可选模型属性绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!