是否对模型做DataTypeAttribute中的验证MVC 3? [英] Does the DataTypeAttribute on a model do validation in MVC 3?
问题描述
默认ASP.net MVC 3 Internet应用程序模板包括以下型号:
The default ASP.net MVC 3 Internet Application template includes the following model:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
在帐户/注册行动它所需要的电子邮件地址,但似乎你可以在此字段中输入任何东西,它会接受它。
In the Account/Register action it is asking for an email address, but it seems you can type anything in this field and it will accept it.
请问数据类型(DataType.EmailAddress)实际上触发验证?现在看来似乎没有。如果不验证类型,然后其目的是什么?
Does the DataType(DataType.EmailAddress) actually trigger validation? It seems like it does not. If it doesn't validate the type, then what is its purpose?
推荐答案
到目前为止我所知,数据类型属性用于格式化,但只有当你使用 @ Html.EditorFor(型号= > model.Field)
So far as I'm aware, the DataType attribute is used for formatting but only when you use @Html.EditorFor(model => model.Field)
.
从示范田,CSHTML例子还有生成的HTML:
Examples from model fields, cshtml and the resulting HTML:
示范田:
[Required]
[DataType(DataType.Text)]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Description")]
public string Desc { get; set; }
CSHTML:
Cshtml:
<div class="form-section">
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
</div>
<div class="form-section">
@Html.LabelFor(x => x.Password)
@Html.EditorFor(x => x.Password)
</div>
<div class="form-section">
@Html.LabelFor(x => x.Desc)
@Html.EditorFor(x => x.Desc)
</div>
生成的HTML:
Resulting HTML:
<div class="form-section">
<label for="Name">Name</label>
<input class="text-box single-line" id="Name" name="Name" type="text" value="">
</div>
<div class="form-section">
<label for="Password">Password</label>
<input class="text-box single-line password" id="Password" name="Password" type="password" value="">
</div>
<div class="form-section">
<label for="Desc">Description</label>
<textarea class="text-box multi-line" id="Desc" name="Desc"></textarea>
</div>
我知道这是一个古老的职位,但也许我可以在这种情况光芒照耀别人说这种方式来
I know it's an old post, but maybe I can shine a light on the situation for others that come this way
这篇关于是否对模型做DataTypeAttribute中的验证MVC 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!