MVC .net xususiyatidagi zarur xususiyat uchun Boolean qiymati

MVC 3 da boolean xususiyati uchun True qiymatini qanday talab qilishim kerak? Men bu erda bo'lganman, qiymatni True bo'lishi kerak

 _
 _
Public Property AcceptAgreement As Boolean

Bog'ning biroz o'lgan taqdirda tuzatishlar bu erda

Ushbu klassni qo'shing

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

Atribut qo'shish

 _
 _
 _
Public Property AcceptAgreement As Boolean
4
Bilaman, bu eski, lekin siz o'zingizning javobingizni javob sifatida qo'shsangiz, men yuqoriga ko'taraman :)
qo'shib qo'ydi muallif JMK, manba

1 javoblar

Kimdir jQuery tekshiruvini qo'shishni xohlasa (tasdiqlash qutisi brauzerda ham, serverda ham tasdiqlansa) BooleanMustBeTrueAttribute sinfini shunday o'zgartirish kerak:

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

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

Asosan, sinf, endi IClientValidatable ham amalga oshiradi va tegishli JS xato xabari va HTML maydoniga qo'shiladigan jQuery validation özniteliğini qaytaradi ("mustbetrue").

Endi, jQuery validatsiyasi ishlash uchun, sahifaga quyidagi j ni qo'shing:

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

Note: I based the previous code on the one used in this answer -> Perform client side validation for custom attribute

Va bu asosda :)

Eski jslarning ishlashi uchun sahifadagi quyidagi JS fayllarini kiritgan bo'lishingiz kerak:

<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. Agar u ishlayotgan bo'lsa, men kodni JScript fayliga Scripts papkasida qo'shishni tavsiya qilaman va barcha JS fayllari bilan paket hosil qilaman.

4
qo'shib qo'ydi