Atributo requerido para un valor entero


Tengo un viewmodel con una propiedad Id

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

Pero creo que este atributo solo funciona para propiedades de cadena.

Cuando no se establece ningún Id, Id tiene el valor 0 y el modelo es válido.

¿Cómo puedo exigir que si no se establece ningún valor para una propiedad int, el modelo no será válido ?

Author: user256034, 2011-07-12

2 answers

Cambie el tipo a Nullable<int> (atajo int?) para permitir null valores.

 41
Author: Julien Lebosquain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-12 10:47:54

Utilice el atributo Range.

Establecer el mínimo en 1 y el máximo en int.MaxValue

[Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
 67
Author: Dubious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-03 19:54:31