你将如何验证在ASP.Net MVC 2复选框? [英] How would you validate a checkbox in ASP.Net MVC 2?
问题描述
使用MVC2,我有一个简单的视图模型包含上视图为复选框呈现一个布尔领域。我想验证用户选中的复选框。在我的视图模型的[必需]属性似乎并没有这样的伎俩。我相信这是因为未选中复选框表单字段实际上并没有在POST过程中传回,因此验证不会在其上运行。
Using MVC2, I have a simple ViewModel that contains a bool field that is rendered on the view as a checkbox. I would like to validate that the user checked the box. The [Required] attribute on my ViewModel doesn't seem to do the trick. I believe this is because the unchecked checkbox form field is not actually transmitted back during the POST, and therefore the validation doesn't run on it.
有处理勾选需要,在MVC2验证的标准方式?或者说我要为它编写自定义验证?我怀疑上面提到的原因,自定义验证不会得到任何执行。我是停留在我的控制器明确检查呢?这似乎凌乱...
Is there a standard way to handle checkbox "required" validation in MVC2? or do I have to write a custom validator for it? I suspect the custom validator won't get executed either for the reason mentioned above. Am I stuck checking for it explicitly in my controller? That seems messy...
任何指导,将AP preciated。
Any guidance would be appreciated.
斯科特
编辑度:正如下面的评论中指出,这是一个同意我们的条款复选框的类型,因此不勾选是一个有效的答案,所以我真的很想找一个被选中验证。
EDIT FOR CLARITY: As pointed out in comments below, this is a "agree to our terms" type of checkbox, and therefore "not checked" is a valid answer, so I'm really looking for an "is checked" validation.
推荐答案
自定义验证程序是要走的路。我会后我的code这是我用来验证用户接受的条款...
a custom validator is the way to go. I'll post my code which I used to validate that the user accepts the terms ...
public class BooleanRequiredToBeTrueAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
return value != null && (bool)value;
}
}
这篇关于你将如何验证在ASP.Net MVC 2复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!