asp.net-mvc - ASP.NET MVC - 将模型值传递给数据注释参数

标签 asp.net-mvc model data-annotations

我想将一个值从我的模型中的一个属性传递到我的数据注释以验证我的密码属性,但我不知道如何实现这一点。当我以这种方式执行此操作时,出现以下错误:

an attribute argument must be a constant expression typeof expression or array

我的型号:
public class LoginModel
{
    public string Voornaam { get; set; }
    public string Achternaam { get; set; }
    public string Gebruikersnaam { get; set; }

    [Password(AttributeVoornaam = this.Voornaam, AttributeAchternaam = this.Achternaam, AttributeGebruikersnaam = this.Gebruikersnaam)]
    public string Wachtwoord { get; set; }
}

在我的数据注释中,我这样做:
public class PasswordAttribute : ValidationAttribute
{
    public string AttributeVoornaam { get; set; }
    public string AttributeAchternaam { get; set; }
    public string AttributeGebruikersnaam { get; set; }

    public override bool IsValid(object value)
    {
        string strValue = value.ToString();

        if (strValue.Contains(AttributeVoornaam.ToLower()) || strValue.Contains(AttributeAchternaam.ToLower()) ||
               strValue.Contains(AttributeGebruikersnaam.ToLower()))
        {
            ErrorMessage = "Uw wachtwoord mag niet uw voornaam, achternaam of gebruikersnaam bevatten.";
            return false;
        }
        else
        {
            return true;
        }
    }
}

最佳答案

您不能将变量值(在编译时未计算的值)传递给属性。它们必须是文字值或常量值。

但是,您可以传递给属性的是您想要在运行时评估的模型属性的名称,然后让您的 IsValid方法通过访问 ValidationContext 在运行时评估这些值。在返回 ValidationResult 的覆盖中的 ValidationAttribute .

或者,如果您总是评估这些相同的属性,那么您可以获取对模型的引用,然后直接使用它:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    LoginModel loginModel = (LoginModel)validationContext.ObjectInstance;

    string strValue = value.ToString();

    if (strValue.Contains(loginModel.Voornaam.ToLower()) || 
        strValue.Contains(loginModel.Achternaam.ToLower()) ||             
        strValue.Contains(loginModel.Gebruikersnaam.ToLower()))
    {
        ErrorMessage = "Uw wachtwoord mag niet uw voornaam, achternaam of gebruikersnaam bevatten.";
        return false;
    }
    else
    {
        return true;
    }
}

关于asp.net-mvc - ASP.NET MVC - 将模型值传递给数据注释参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21680554/

相关文章:

asp.net-mvc - 我应该始终使用 View 模型还是可以使用 ViewData?

ruby-on-rails - 在 Rails 中的何处放置创建模型和关联逻辑?

asp.net-mvc - DataAnnotations StringLength属性MVC-没有最大值

asp.net-mvc - 如何在不重复代码的情况下实现业务和 View 验证?

c# - 使用 Jquery 单击按钮的客户端数据注释验证

asp.net-mvc - 使用 asp.net mvc 使某个枚举值的验证失败

c# - 无法创建 Controller ,依赖注入(inject)

c# - 在 JSON post 请求中提供 AntiForgeryToken

python - DJango 中的模型流派

php - Laravel 授权策略 AccessDeniedHttpException 此操作未经授权