2011-10-28 54 views
4

對於使用.NET的MVC 3中的boolean屬性,我該如何要求值True? 這是我在哪裏,我需要的值是True othewise它不是有效對於MVC .net屬性上的必需屬性爲True的布爾值

<Required()> _ 
<DisplayName("Agreement Accepted")> _ 
Public Property AcceptAgreement As Boolean 

這裏是在情況下,修復鏈接死亡哪天

添加該類

Public Class BooleanMustBeTrueAttribute Inherits ValidationAttribute 

    Public Overrides Function IsValid(ByVal propertyValue As Object) As Boolean 
     Return propertyValue IsNot Nothing AndAlso TypeOf propertyValue Is Boolean AndAlso CBool(propertyValue) 
    End Function 

End Class 

添加屬性

<Required()> _ 
<DisplayName("Agreement Accepted")> _ 
<BooleanMustBeTrue(ErrorMessage:="You must agree to the terms and conditions")> _ 
Public Property AcceptAgreement As Boolean 
+0

我知道這是舊的,但如果你添加你的解決方案作爲答案,我會upvote :) – JMK

回答

4

如果有人有興趣添加jquery驗證(這樣複選框無論是在瀏覽器和服務器驗證的),你應該修改BooleanMustBeTrueAttribute類,像這樣:

public class BooleanMustBeTrueAttribute : ValidationAttribute, IClientValidatable 
{ 
    public override bool IsValid(object propertyValue) 
    { 
     return propertyValue != null 
      && propertyValue is bool 
      && (bool)propertyValue; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     yield return new ModelClientValidationRule 
     { 
      ErrorMessage = this.ErrorMessage, 
      ValidationType = "mustbetrue" 
     }; 
    } 
} 

基本上,類現在還實現IClientValidatable,並返回相應的js錯誤消息和將被添加到HTML字段(「mustbetrue」)的jquery驗證屬性。現在

,爲了使jQuery驗證工作,添加以下JS頁面:

jQuery.validator.addMethod('mustBeTrue', function (value) { 
    return value; // We don't need to check anything else, as we want the value to be true. 
}, ''); 

// and an unobtrusive adapter 
jQuery.validator.unobtrusive.adapters.add('mustbetrue', {}, function (options) { 
    options.rules['mustBeTrue'] = true; 
    options.messages['mustBeTrue'] = options.message; 
}); 

注:我根據在這個答案中使用的一個以前的代碼 - >Perform client side validation for custom attribute

而這基本上它:)

記住,以前的JS工作,你必須包含在頁面下面的js文件:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> 

P.S.當你有它的工作,我實際上建議將代碼添加到腳本文件夾中的js文件,並創建一個包含所有js文件的包。