Asp.net mvc 基于验证对象的自定义属性名称

Asp.net mvc 基于验证对象的自定义属性名称,asp.net-mvc,fluentvalidation,Asp.net Mvc,Fluentvalidation,我有以下几节课,例如,它们有点简化 class LineInfo { Id, LineNumber, SubAccountNumer, MobileNumber } class SuspendLinesVM{ public List<LineInfo> Lines{ get;set; } } class-LineInfo { 身份证件 行号, 子账户, 移动电话 } 类SuspendLinesVM{ 公共列表行{get;set;

我有以下几节课,例如,它们有点简化

class LineInfo
{   
    Id,
    LineNumber,
    SubAccountNumer,
    MobileNumber
}

class SuspendLinesVM{
    public List<LineInfo> Lines{ get;set; }
}
class-LineInfo
{   
身份证件
行号,
子账户,
移动电话
}
类SuspendLinesVM{
公共列表行{get;set;}
}
我在操作中收到SuspendLinesVM,所有行都是从客户端动态创建的。表单中属于具体LineInfo的每个元素的名称都带有模板“lineid{Id}\u ElementName”。所以他们以如下形式出现在我面前:

lineid0001\u线号

行ID0001_子科目编号

lineid0001\u手机号码

lineid0021\U线号

lineid0021_子科目编号

lineid0021\u手机号码

当验证过程中出现错误时,我需要一种方法来设置请求中出现的failed属性,以突出显示视图中的无效字段

我留下的问题让我感到困惑

 public class LineInfoValidator: AbstractValidator<LineInfo>
    {
        public LineInfoValidator()
        {
            RuleFor(m => m.LineNumber)
                .NotEmpty().WithMessage("Line # is required").OverridePropertyName( ??? ) 
                .InclusiveBetween(1, 9999).WithMessage("Line # must be in range [1, 9999]").OverridePropertyName( ??? )
...
公共类LineInfoValidator:AbstractValidator
{
公共LineInfoValidator()
{
规则(m=>m.LineNumber)
.NotEmpty().WithMessage(“需要行”).OverridePropertyName(???)
.inclusiveBeween(1,9999)。WithMessage(“行#必须在[1,9999]范围内”)。OverridePropertyName(?)
...
我需要一种类似*(instance,propertyName)=>返回string.format('lineid{0}{1}',instance.Id,propertyName)*的方法


有什么想法吗?

鉴于您正在使用FluentValidator,您应该能够在SuspendedLinesVM对象上设置集合验证器,如下所示:

public class SelectedLinesVMValidator : AbstractValidator<SelectedLinesVM>
{
    public SelectedLinesVMValidator()
    {
        RuleFor(x=>x.Lines).SetCollectionValidator(new LineInfoValidator());
    }
}
public类SelectedLinesVMValidator:AbstractValidator
{
public SelectedLinesVMValidator()
{
RuleFor(x=>x.Lines).SetCollectionValidator(newlineInfoValidator());
}
}

如果执行此操作,则将返回与失败属性的索引相关的错误集合。

使用“WithState”方法解决。多亏了Jeremy!他的解决方案就在这里

JeremyS
2011年11月10日下午5:16

不幸的是,这是不受支持的

当验证器被实例化时,属性名只解析一次,而不是执行验证器时生成的错误消息。在这种情况下,您需要检查正在验证的实例以生成属性名,这实际上是不可能的-您能够得到的最接近的方法是使用WithState方法to将某些自定义状态与故障关联:

RuleFor(x => x.LineNumber)
    .NotEmpty()
    .WithState(instance => string.Format("lineid_{0}_LineNumber", instance.Id));
调用验证器并返回ValidationResult后,可以从ValidationFailure上的CustomState属性中检索该结果

杰里米


这是正确的。但对于我的集合中的所有LineInfo,每个属性名称都将是相同的,如“LineNumber”、“SubAccountNumer”等。视图不会区分错误所属的LineInfo,也不会呈现错误,因为属性名称必须类似于“lineid0001\U LineNumber”。如果这么简单的话:)