现在我有一个包含三个输入列表的viewmodel; textboxinput,dropdownlistinput和checkboxinput。这些列表中的每一个都是输入对象列表,其中包含四个值; paramenums,paramname,paramtype和value。我使用这些输入列表在表单上生成可变数量的字段,具体取决于每个列表包含多少个对象。
我目前的问题是我不确定如何使用流畅的验证来验证列表对象中的变量。我知道每个列表的行为应该如何返回Nothing,但我不知道如何使用FluentValidation编写该行为。
输入模型:
Public Class Input
Property value As String
Property ParamName As String
Property ParamType As String
Property ParamEnums As List(Of String)
End Class
ParamViewModel:
Imports FluentValidation
Imports FluentValidation.Attributes
<Validator(GetType(ParamViewModelValidator))> _
Public Class ParamViewModel
Property TextBoxInput As List(Of Input)
Property DropdownListInput As List(Of Input)
Property CheckBoxInput As List(Of Input)
End Class
我的观点:
@Modeltype SensibleScriptRunner.ParamViewModel
<h2>Assign Values to Each Parameter</h2>
@Code
Using (Html.BeginForm("Index", "Parameter", FormMethod.Post))
@<div>
<fieldset>
<legend>Parameter List</legend>
@For i = 0 To (Model.TextBoxInput.Count - 1)
Dim iterator = i
@Html.EditorFor(Function(x) x.TextBoxInput(iterator), "TextInput")
Next
@For i = 0 To Model.DropdownListInput.Count - 1
Dim iterator = i
@Html.EditorFor(Function(x) x.DropdownListInput(iterator), "EnumInput")
Next
@For i = 0 To Model.CheckBoxInput.Count - 1
Dim iterator = i
@Html.EditorFor(Function(x) x.CheckBoxInput(iterator), "CheckBoxInput")
Next
<p>
<input type="submit" value="Query Server"/>
</p>
</fieldset>
</div>
Html.EndForm()
End Using
End Code
其中一个编辑模板的示例:
@modeltype SensibleScriptRunner.Input
@Code
@<div class="editor-label">
@Html.LabelFor(Function(v) v.value, Model.ParamName)
</div>
@<div class="editor-field">
@Html.TextBoxFor(Function(v) v.value)
</div>
End Code
当前的FluentValidation代码:
Imports FluentValidation
Public Class ParamViewModelValidator
Inherits AbstractValidator(Of ParamViewModel)
Public Sub New()
RuleFor(Function(x) x.TextBoxInput).NotEmpty.[When](Function(x) Not IsNothing(x.TextBoxInput))
RuleFor(Function(x) x.DropdownListInput).NotEmpty.[When](Function(x) Not IsNothing(x.DropdownListInput))
RuleFor(Function(x) x.CheckBoxInput).NotEmpty.[When](Function(x) Not IsNothing(x.CheckBoxInput))
End Sub
End Class
我想要做的事情是确认在我的每个列表中的每个对象中,它们都具有一个并非一无所有的值属性。我可以通过验证输入模型来做到这一点吗?现在,代码用于确认列表本身不为空,但列表中的对象仍然可以包含所有空值。有一个微不足道的方法来做到这一点?
或者,我应该以不同的方式设置我的代码吗?
答案 0 :(得分:1)
好吧,我明白了。对于任何好奇的人,我所要做的就是添加一个inputvalidator类。
Imports FluentValidation
Public Class InputValidator
Inherits AbstractValidator(Of Input)
Public Sub New()
RuleFor(Function(x) x.value).NotEmpty()
RuleFor(Function(x) x.ParamName).NotEmpty()
RuleFor(Function(x) x.ParamType).NotEmpty()
End Sub
End Class
将此添加到我的输入模型解决了所有问题。我不确定代码实际检查此验证的位置(我的编辑器模板指向输入作为模型,也许这与它有关;也可能是当我的paramviewmodelvalidator检查列表是否有效时,它还检查该列表中每个对象的标准(我认为这是这个))。无论如何,如果有人遇到类似的问题,这是一个解决方案。