范围注释介于无和100之间? [英] Range annotation between nothing and 100?

查看:83
本文介绍了范围注释介于无和100之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个[Range]注解,如下所示:

I have a [Range] annotation that looks like this:

[Range(0, 100)]
public int AvailabilityGoal { get; set; }

我的网页如下:

<%=Html.TextBoxFor(u => u.Group.AvailabilityGoal)%>

它可以正常工作,我只能输入0到100之间的值,但是我也希望输入框是可选的,如果输入框为空,则用户不会收到验证错误.这与范围无关,只是因为类型是整数.如果用户将其保留为空,则应该使AvailabilityGoal = 0,但我不想强迫用户输入零.

It works as it should, I can only enter values between 0 and 100 but I also want the input box to be optional, the user shouldn't get an validation error if the input box is empty. This has nothing to do with the range but because the type is an integer. If the user leaves it empty it should make AvailabilityGoal = 0 but I don't want to force the user to enter a zero.

我尝试了这个,但是(显然)没有用:

I tried this but it (obviously) didn't work:

[Range(typeof(int?), null, "100")]

是否可以通过数据注释或其他方式解决此问题?

Is it possible to solve this with Data Annotations or in some other way?

谢谢.

鲍比

推荐答案

您不必更改[Range]属性,因为当给定一个空值时,[Range]和其他内置的DataAnnotations验证器将无效.只需将属性本身设置为 int?类型,而不是 int .始终会自动要求使用不可为null的ValueType属性(例如int).

You shouldn't have to change the [Range] attribute, as [Range] and other built-in DataAnnotations validators no-op when given an empty value. Just make the property itself of type int? rather than int. Non-nullable ValueType properties (like int) are always automatically required.

这篇关于范围注释介于无和100之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆