I am trying to validate hidden integer property can you please suggest better way
public class Model
{
[Display(Name="Theme"),Required(ErrorMessage="Please choose your theme")]
public int ThemeId { get; set; }
}
In view
@Html.Hidden(m=>m.ThemeId)
And this output <input type="hidden" bbla bla value="0"/>
Problem is currently this field is valid because 0 is default value of int property so every required in property is default valid. So I have to make it invalid.
My Solution is
Simply using Range(1,int.MaxValue)
attribute for that property.
I am just asking to know that is it best solution to this problem or not . If not can you please po开发者_运维技巧int better solution.
I've hit this same problem and haven't come up with a better solution.
It's perfectly valid as you are saying that the range of values for this property is 1..MaxInt
.
The only other solution I can see is to make it a nullable integer and then testing that the value is not null. However, that would include the value zero and negative values so you still have to check that it's a positive integer.
There are two alternatives:
- Use
Nullable
properties (int?
in this case) - Use
string
to allow empty fields
For this scenario, the preferred way is to make the property in the ViewModel nullable, and mark it as required.
The question Should my viewmodel value type properties be nullable? also contains some information and opinions on both approaches.
精彩评论