当前的项目:
- ASP.NET 4.5.1
- MVC 5
我需要知道我是否可以嵌套When()
这样的语句:
When(x => x.Cond1 == val1,
() => {
When(x => x.SubCond1 == SubVal1,
() => {
When(x => x.Final1 == finalVal1,
() => {
RuleFor(x => x.Field1)
.NotEmpty().WithMessage("Should not be empty");
// a few more here
});
When(x => x.Final2 == finalVal2,
() => {
RuleFor(x => x.Field8)
.NotEmpty().WithMessage("Should not be empty");
// a few more here
});
});
When(x => x.SubCond2 == SubVal2,
() => {
RuleFor(x => x.Field16)
.NotEmpty().WithMessage("Should not be empty");
// a few more here
});
});
因为我最不想做的就是像这样装饰 30 多个表单字段:
RuleFor(x => x.Field1)
.NotEmpty().WithMessage("Should not be empty")
.When(x => x.Cond1 == val)
.When(x => x.SubCond1 == SubVal1)
.When(x => x.Final1 == finalVal1);
那是站不住脚的。
这些条件本身都不需要验证,因为它们实际上都不是用户可编辑的字段(只是用户可选择的值);我只需要将它们与已知值进行比较。如果这实际上更合适,我会使用 if/else 语句,但事实并非如此。
该模型基本上是扁平的,只有第二层When()
代表导入的模型,第三层是处理导入模型中特定字段的不同方式。