我有多次使用此表单类'Value','Maximum'字段仅在某些情况下使用。如果'Show'属性为true并且显示'Maximum'字段,我需要验证'Maximum'是否有值。提前谢谢!
型号:
public class Value
{
public bool Show { get; set; }
public bool Required { get; set; }
[RequiredIf("Show", Domain.Comparison.IsEqualTo, true, ErrorMessageResourceType = typeof(Resources.ErrorMessages), ErrorMessageResourceName = "AuthorLabelIsRequired")]
public string Label { get; set; }
public string Description { get; set; }
[RequiredIf("Show", Domain.Comparison.IsEqualTo, true, ErrorMessageResourceType = typeof(Resources.ErrorMessages), ErrorMessageResourceName = "AuthorLabelIsRequired")]
public int? Maximum { get; set; }
}
HTML:
<tr>
<td>@Html.EnumString(Model.Data.DateSection.Key)</td>
<td>@Html.CheckBoxFor(m => m.Data.DateSection.Value.Show)</td>
<td>@Html.CheckBoxFor(m => m.Data.DateSection.Value.Required)</td>
<td>
@Html.TextBoxFor(m => m.Data.DateSection.Value.Label, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Data.DateSection.Value.Label)
</td>
<td>@Html.TextBoxFor(m => m.Data.DateSection.Value.Description, new { @class = "form-control" })</td>
<td></td>
</tr>
<tr>
<td>@Html.EnumString(Model.Data.DescriptionSection.Key)</td>
<td>@Html.CheckBoxFor(m => m.Data.DescriptionSection.Value.Show)</td>
<td>@Html.CheckBoxFor(m => m.Data.DescriptionSection.Value.Required)</td>
<td>
@Html.TextBoxFor(m => m.Data.DescriptionSection.Value.Label, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Data.DescriptionSection.Value.Label)
</td>
<td>@Html.TextBoxFor(m => m.Data.DescriptionSection.Value.Description, new { @class = "form-control" })</td>
<td>
@Html.TextBoxFor(m => m.Data.DescriptionSection.Value.Maximum, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Data.DescriptionSection.Value.Maximum)
</td>
</tr>
答案 0 :(得分:1)
在ASP.NET MVC中处理条件验证实际上是一种相当优雅的方式。你的模型最终会看起来像这样:
public class Value : IValidatableObject {
public bool Show { get; set; }
public bool Required { get; set; }
[RequiredIf("Show", Domain.Comparison.IsEqualTo, true, ErrorMessageResourceType = typeof(Resources.ErrorMessages), ErrorMessageResourceName = "AuthorLabelIsRequired")]
public string Label { get; set; }
public string Description { get; set; }
[RequiredIf("Show", Domain.Comparison.IsEqualTo, true, ErrorMessageResourceType = typeof(Resources.ErrorMessages), ErrorMessageResourceName = "AuthorLabelIsRequired")]
public int? Maximum { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (this.Show && !this.Maximum.HasValue) {
yield return new ValidationResult("You must specify a maximum value");
}
}
}
注意模型:
IValidateableObject
Validate
的方法,它返回类型IEnumerable<ValidationResult>
在模型绑定过程中,将自动调用此方法,如果返回验证结果,则ModelState
将不再有效。因此,在您的控制器中使用此熟悉的代码将确保您不采取任何操作,除非您的自定义条件检查:
public class SomeController {
public ActionResult SomeAction() {
if (ModelState.IsValid) {
//Do your stuff!
}
}
}