ASP.NET MVC-将模型值传递给数据注释参数 [英] ASP.NET MVC - Pass model value to data annotation parameter
问题描述
我想将模型中的一个属性值传递给数据注释以验证密码属性,但是我不知道如何实现此目的.以这种方式执行此操作时,出现以下错误:
I want to pass a value from one of my properties in my model to my data annotation to validate my password property, but I have no idea how I can achieve this. When I am doing this at this way I get the following error:
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; }
}
在我的数据注释中,我正在这样做:
And in my data annotation I am doing this:
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;
}
}
}
推荐答案
您不能将变量值(在编译时未评估的值)传递到属性中.它们必须是文字值或常量值.
You can't pass variable values (values that are not evaluated at compile-time) into attributes. They have to be literal values or constant values.
可以传递给属性的是您要在运行时评估的模型属性的名称,然后让您的IsValid
方法在以下位置评估这些值通过访问覆盖中的ValidationContext
并返回ValidationAttribute
的ValidationResult
来运行时.
What you can pass into attributes, though, are the names of the properties of your model that you want to evaluate at run-time, and then have your IsValid
method evaluate these values at run-time by accessing the ValidationContext
in the override that returns a ValidationResult
of ValidationAttribute
.
或者,如果您始终在评估这些相同的属性,则只需获取对模型的引用,然后直接使用它即可:
Or, if you are always evaluating these same properties, then you can just grab the reference to your model, and use that directly:
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-将模型值传递给数据注释参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!