MVC 3根据存储在DB中的用户首选项进行自定义验证属性检查

时间:2011-11-29 17:16:35

标签: asp.net-mvc-3

根据存储在数据库中的用户首选项,我有一个可能需要或可能不需要的字段。为了解决这个问题,我创建了一个自定义验证属性,但我不知道如何根据用户偏好检查该字段是否真正需要。

我尝试通过控制器和放大器在我的视图模型上设置“IsRequired”属性。检查自定义属性中的值,但该属性始终为false,因为在设置属性之前验证已触发。

使用数据注释如何在验证开始之前/之后设置“IsRequired”属性?我是否应该检查字段是否已经传递给控制器​​而不是使用数据注释?

视图模型:

Public Class MyViewModel
    <MyCustomValidationAttribute("IsMyFieldRequired")>
    Public Property MyFieldThatMayOrMayNotBeRequired As String
    Public Property IsMyFieldRequired As Boolean

    Public Sub New(objectUsedToSetIsMyFieldRequired As UserPreferences)
        'Set IsMyFieldRequired based on passed in user preferences
    End Sub
End Class

自定义验证属性:

Public Class MyCustomValidationAttribute
    Inherits ValidationAttribute

    Private _otherPropertyName As String

    Public Sub New(otherPropertyName As String)
        Me._otherPropertyName = otherPropertyName 
    End Sub

    Protected Overrides Function IsValid(value As Object, validationContext As System.ComponentModel.DataAnnotations.ValidationContext) As System.ComponentModel.DataAnnotations.ValidationResult
        Dim basePropertyInfo As System.Reflection.PropertyInfo = validationContext.ObjectType.GetProperty(_otherPropertyName)
        Dim isRequired As Boolean = Not CBool(basePropertyInfo.GetValue(validationContext.ObjectInstance, Nothing))
        '
        If isRequired AndAlso value Is Nothing Then Return New ValidationResult(Me.ErrorMessage)
        '
        Return Nothing
    End Function
End Class

1 个答案:

答案 0 :(得分:1)

您不应该在验证中进行任何数据库访问。您可以使用远程验证并调用操作方法来查找值,或者您可以在模型中设置属性。您可以使用许多人创建的“比较”自定义验证的变体。这是一个例子http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

相关问题