use*_*034 60 asp.net-mvc data-annotations
我有一个带Id属性的viewmodel
[Required]
public int Id { get; set; }
Run Code Online (Sandbox Code Playgroud)
但我认为这个属性仅适用于字符串属性.
如果未设置Id,则Id的值为0且模型有效.
如果没有设置int属性的值,我该如何强制执行,模型将无效?
Lee*_*ith 78
使用Range属性.
将最小值设置为1,最大值设置为 int.MaxValue
[Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
Run Code Online (Sandbox Code Playgroud)
Jul*_*ain 46
将类型更改为Nullable<int>(快捷方式int?)以允许null值.
对于 .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.");
}
}
Run Code Online (Sandbox Code Playgroud)
在模型中使用这样的 Id 属性:
public class MessageForUpdate
{
[Required, Id]
public int UserId { get; set; }
[Required]
public string Text { get; set; }
[Required, Id]
public int ChannelId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当 Id 为<= 0以下错误消息时返回:
UserId must be an integer greater than 0.
无需验证该值是否小于 int.MaxValue(尽管在消息中显示这一点很好),因为即使该值是 int.MaxValue + 1,API 也会默认在到达此之前返回此错误:
The JSON value could not be converted to System.Int32
这与 @Lee Smith 的答案类似,但使 0 成为有效输入,这在某些情况下可能有用。
你可以做的是将 int 值初始化为另一个值然后 0,如下所示:
[Range(0, int.MaxValue)]
public int value{ get; set; } = -1;
Run Code Online (Sandbox Code Playgroud)
甚至可以通过这样做来支持除 int.MinValue 之外的所有值:
[Range(int.MinValue + 1, int.MaxValue)]
public int value{ get; set; } = int.MinValue;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29269 次 |
| 最近记录: |