如何使用 DataAnnotations 处理 ASP.NET MVC 2 中的布尔值/复选框? [英] How to handle Booleans/CheckBoxes in ASP.NET MVC 2 with DataAnnotations?

查看:32
本文介绍了如何使用 DataAnnotations 处理 ASP.NET MVC 2 中的布尔值/复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的视图模型:

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; }
}

视图标记代码:

<%= Html.CheckBoxFor(m => m.AgreesWithTerms) %>
<%= Html.LabelFor(m => m.AgreesWithTerms)%>

结果:

不执行验证.到目前为止还可以,因为 bool 是一种值类型并且从不为 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

模板只能用于字段访问、属性访问、单维数组索引或单参数自定义索引器表达式."

"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;
    }
}

这篇关于如何使用 DataAnnotations 处理 ASP.NET MVC 2 中的布尔值/复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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