如何处理布尔/检查框ASP.NET MVC 2 DataAnnotations? [英] How to handle Booleans/CheckBoxes in ASP.NET MVC 2 with DataAnnotations?
本文介绍了如何处理布尔/检查框ASP.NET MVC 2 DataAnnotations?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个视图模型是这样的:
I've got a view model like this:
public class SignUpViewModel
{
[Required(ErrorMessage = "Bitte lesen und akzeptieren Sie die AGB.")]
[DisplayName("Ich habe die AGB gelesen und akzeptiere diese.")]
public bool AgreesWithTerms { get; set; }
}
视图标记code:
The view markup code:
<%= Html.CheckBoxFor(m => m.AgreesWithTerms) %>
<%= Html.LabelFor(m => m.AgreesWithTerms)%>
结果:
没有验证执行。这没关系,到目前为止,因为布尔是值类型,并不能为null。但是,即使我做AgreesWithTerms为空的,它不会工作,因为编译器呼喊
No validation is executed. That's okay so far because bool is a value type and never null. But even if I make AgreesWithTerms nullable it won't work because the compiler shouts
模板只能与现场访问,访问属性,一维数组的索引,或单参数自定义索引前pressions使用。
"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."
那么,什么是处理这个正确的方式?
So, what's the correct way to handle this?
推荐答案
我通过创建一个自定义属性得到它:
I got it by creating a custom attribute:
public class BooleanRequiredAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
return value != null && (bool) value;
}
}
这篇关于如何处理布尔/检查框ASP.NET MVC 2 DataAnnotations?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文