C# MVC - 根据模型动态获取属性名称

标签 c# asp.net-mvc validation reflection custom-attributes

在我的 MVC 项目中,我有不同的自定义验证属性。其中之一是检查一个属性的值与另一个属性的值。

正如许多文章中所述,我添加了类似的东西

result.ValidationParameters.Add("otherproperty", _otherPropertyHtml);
result.ValidationParameters.Add("comparetype", _compareType);
result.ValidationParameters.Add("equalitytype", _equalityType);

到返回的 ModelClientValidationRule 对象。

我现在的问题是,如果我要检查的属性被封装在另一个对象中,验证将不起作用。

如果我创建类似的东西

@Html.TextBoxFor(m => m.ValueOne)
@Html.TextBoxFor(m => m.ValueTwo)

验证将在呈现时正常工作

data-val-otherproperty="ValueTwo"

我的问题是以下

@Html.TextBoxFor(m => m.IntermediateObject.ValueOne)
@Html.TextBoxFor(m => m.IntermediateObject.ValueTwo)

这将呈现两个名为 IntermediateObject_ValueOneIntermediateObject.ValueTwo 的文本框。但第一个文本框仍然是 data-val-otherproperty="ValueOne"。

如何实现 data-val-otherproperty 始终具有其他属性的正确名称?

我的想法是像 HtmlHelper<>.NameFor(m => ...) 或使用反射的东西?

更新 1 - 根据评论要求添加代码

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = false)]
public class CustomCompareToOther : ValidationAttribute, IClientValidatable
{
    // private backing-field
    private readonly string _otherPropertyName;

    // constructor
    public OemCompareToOther(string otherPropertyName)
    {
        _otherPropertyName = otherPropertyName;
    }

    // implementation of IClientValidatable
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var result = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                ValidationType = "customcomparetoother"
            };

        // add the property-name so it is known when rendered for client-side validation
        result.ValidationParameters.Add("otherproperty", _otherPropertyHtml); // here I would need IntermediateObject.ValueTwo instead of only ValueTwo

        yield return result;
    }
}

模型级别的用法是

public class MyModel
{
    [CustomCompareToOther("ValueOTwo", CompareType.NotEqual, PropertyType.String)]
    public string ValueOne { get; set; }    

    [CustomCompareToOther("ValueTwo", CompareType.NotEqual, PropertyType.String)]
    public string ValueTwo { get; set; }
}

我将放入我的 View 中的内容类似于

public class ViewModel
{
    public MyModel IntermediateObject { get; set; }
}

例如使用返回 View (新 ViewModel())。 所以,在呈现的 HTML 中我会有一个输入

<input type="text" name="IntermediateObject_ValueOne" id="IntermediateObject.ValueOne" data-val-customcomparetoother-otherpropertyname="ValueTwo" />
<input type="text" name="IntermediateObject_ValueTwo" id="IntermediateObject.ValueTwo" data-val-customcomparetoother-otherpropertyname="ValueOne" />

但我需要

<input type="text" name="IntermediateObject_ValueOne" id="IntermediateObject.ValueOne" data-val-customcomparetoother-otherpropertyname="IntermediateObject.ValueTwo" />
<input type="text" name="IntermediateObject_ValueTwo" id="IntermediateObject.ValueTwo" data-val-customcomparetoother-otherpropertyname="IntermediateObject.ValueOne" />

在 html 中,以便 javascript-validation 可以正确获取其他属性。

最佳答案

您可以使用 [Compare("PropertyName")] 数据注释。

您的 View 模型中的示例:

[Display(Name = "New Password")]
[DataType(DataType.Password)]
public string NewPassword { get; set; }

[Display(Name = "Confirm Password")]
[DataType(DataType.Password)]
[Compare("NewPassword")]
public string PasswordConfirmation { get; set; }

请记住将 System.ComponentModel.DataAnnotations 命名空间添加到您的 using 语句中

关于C# MVC - 根据模型动态获取属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809650/

相关文章:

c# - 存储 UI 设置的最佳实践?

c# - MVC ViewModel 包含一个字典,用于将空值返回给 Controller 的字段

jquery - 验证表单已填写,HTML jQuery

.net - 我如何向类(class)用户表明验证要求?

c# - 如何判断我的进程是否以管理员身份运行?

c# - 如何(或我可以)列出通用列表中对象的属性,并将其显示在组合框中

asp.net - 何时使用强类型 View ?

javascript - 在 javascript/jquery 中读取文件

c# - 如何显示服务器端验证错误消息?

c# - 与表 2 相关的 GridView 表 1