如何在我的MVC字段中添加验证?

Jes*_*ica 0 asp.net-mvc asp.net-mvc-3

我有以下定义:

public class Menu
{
    [DisplayName("Control")]
    public int Control { get; set; }
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

  @Html.TextBoxFor(x => x.Control, new { id = "control" })
Run Code Online (Sandbox Code Playgroud)

我可以为订单指定一个范围吗?我希望订单是0到999之间的数字.

还有可能让我创建的文本框只有三个字符的空间吗?

Iri*_*dio 5

Is it possible for me to specify a range for the order? I would like the order to be a number between 0 and 999. 
Run Code Online (Sandbox Code Playgroud)

使用RangeAttribute

[DisplayName("Control")]
[Range(0, 99, ErrorMessage = "{0} must be between {1} and {2}")]
public int Control { get; set; }
Run Code Online (Sandbox Code Playgroud)

对于第二个问题

Also is it possible for me to make the textbox that gets created just have space for three characters?
Run Code Online (Sandbox Code Playgroud)

使用StringLengthAttribute

[StringLength(3, ErrorMessage="{0} must be {1} characters"]
[DisplayName("Control")]
[Range(0, 99, ErrorMessage = "{0} must be between {1} and {2}")]
public int Control { get; set; }
Run Code Online (Sandbox Code Playgroud)

如果需要,您还可以指定minumun chars长度

[StringLength(10, minimumLength=5, ErrorMessage="{0} must be between {1} and {2} characters"]
public int Control { get; set; }
Run Code Online (Sandbox Code Playgroud)