asp.net-mvc 整数值的必需属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6662976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:19:37  来源:igfitidea点击:

Required attribute for an integer value

asp.net-mvcdata-annotations

提问by user256034

I have a viewmodel with an Id property

我有一个带有 Id 属性的视图模型

[Required]
public int Id { get; set; }

But I think this attribute is working only for string properties.

但我认为此属性仅适用于字符串属性。

When no Id is set, Id has value 0 and the model is valid.

未设置Id时,Id值为0,模型有效。

How can I enforce that if no value for a int property is set, the model will be invalid ?

如果没有设置 int 属性的值,我如何强制执行该模型将无效?

采纳答案by Julien Lebosquain

Change the type to Nullable<int>(shortcut int?) to allow nullvalues.

将类型更改为Nullable<int>(shortcut int?) 以允许null值。

回答by Lee Smith

Use the RangeAttribute.

使用Range属性。

Set minimum to 1 and maximum to int.MaxValue

将最小值设置为 1,将最大值设置为 int.MaxValue

[Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]

回答by Dustin C

For .NET Core (and maybe earlier versions) you can also create a custom attribute to perform the range validation for ease of reuse:

对于 .NET Core(可能还有更早的版本),您还可以创建一个自定义属性来执行范围验证,以便于重用:

public class Id : ValidationAttribute
{
    protected override ValidationResult IsValid(
        object value,
        ValidationContext validationContext)
    {
        return Convert.ToInt32(value) > 0 ?
            ValidationResult.Success :
            new ValidationResult($"{validationContext.DisplayName} must be an integer greater than 0.");
    }
}

Use the Id attribute like this in your model:

在您的模型中使用这样的 Id 属性:

public class MessageForUpdate
{
    [Required, Id]
    public int UserId { get; set; }
    [Required]
    public string Text { get; set; }
    [Required, Id]
    public int ChannelId { get; set; }
}

When the Id is <= 0this error message is returned:

当 Id 是<= 0此错误消息时返回:

UserId must be an integer greater than 0.

UserId must be an integer greater than 0.

No need to verify that the value is less than int.MaxValue (although it is nice to display that in the message) because the API will return this error by default before it gets this far even if the value is int.MaxValue + 1:

无需验证该值是否小于 int.MaxValue(尽管在消息中显示该值很好),因为即使该值是 int.MaxValue + 1,API 也会在它达到这个程度之前默认返回此错误:

The JSON value could not be converted to System.Int32

The JSON value could not be converted to System.Int32

回答by Dominik Kozio?

If yo are using database. You should use attribute [Key] and [DatabaseGenerated(DatabaseGenerated.Identity)]. Id shouldn't be NULLABLE

如果您正在使用数据库。您应该使用属性 [Key] 和 [DatabaseGenerated(DatabaseGenerated.Identity)]。Id 不应该为 NULLABLE