首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

ASP.NET MVC ValidationAttribute获取其他属性显示名称

作为一个云计算领域的专家,我可以为您提供关于ASP.NET MVC ValidationAttribute获取其他属性显示名称的信息。

ValidationAttribute是ASP.NET MVC中的一个特性,用于定义自定义验证规则。在ValidationAttribute中,可以使用DisplayAttribute来获取其他属性的显示名称。

以下是一个示例代码,展示如何在ValidationAttribute中获取其他属性的显示名称:

代码语言:csharp
复制
public class CustomValidationAttribute : ValidationAttribute
{
    public string OtherPropertyName { get; set; }

    public CustomValidationAttribute(string otherPropertyName)
    {
        OtherPropertyName = otherPropertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var otherProperty = validationContext.ObjectType.GetProperty(OtherPropertyName);
        var displayName = otherProperty.GetCustomAttribute<DisplayAttribute>()?.Name;

        // 在这里编写自定义验证逻辑,并使用displayName作为其他属性的显示名称
    }
}

在上面的代码中,我们首先通过validationContext.ObjectType.GetProperty(OtherPropertyName)获取其他属性的PropertyInfo对象。然后,我们使用GetCustomAttribute<DisplayAttribute>()?.Name方法获取该属性的显示名称。

需要注意的是,在使用ValidationAttribute时,需要将其应用于相应的属性上,例如:

代码语言:csharp
复制
public class MyModel
{
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [CustomValidation(OtherPropertyName = "FirstName")]
    public string LastName { get; set; }
}

在上面的代码中,我们将CustomValidationAttribute应用于LastName属性上,并将FirstName作为其他属性的名称传递给它。在CustomValidationAttribute中,我们可以使用DisplayAttribute获取FirstName属性的显示名称。

希望这些信息能够帮助您解决问题。如果您有其他问题,请随时提问。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券