有一个文本框和一个下拉列表框。如果选择了文本框,则显示对下拉菜单的验证,这意味着也应选择下拉菜单;如果选择了下拉菜单,则显示对文本框的验证,这意味着也应选择文本框。 我希望在Model类上做到这一点,并且条件应该在mvc中可见。
<table class="simple">
<thead>
<tr>
<th colspan="2">Heading </th>
</tr>
</thead>
<tbody>
<tr>
<td>
@Html.TextBoxFor(model.prop4,new
{@class = "form- control font-9 p-1" })
</td>
<td>
@(Html.Kendo().DropDownListFor(m =>
m.prop3))
.DataTextField("Type")
.DataValueField("Id")
.OptionLabel(PleaseSelect)
.HtmlAttributes(new { @class = "form-control" }))
</td>
</tr>
</tbody>
</table>
模型类为-
public class ViewModel
{
public int? prop1 { get; set; }
public decimal? prop2 { get; set; }
public int? prop3 { get; set; }
public decimal? prop4 { get; set; }
}
答案 0 :(得分:0)
创建一个新的班级
public class Custom : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//Get your model and do magic!
var model = (yourmodel)validationContext.ObjectInstance;
//Your condtions
if ((model.prop1== null && model.prop2 == null) || (model.prop1!= null && model.prop2 != null))
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("You must select both of them");
}
}
}
现在添加您的自定义注释
public class RefractionFinalViewModel
{
[custom]
[Display(Name = "Select type")]
public int? prop1 { get; set; }
public decimal? prop2 { get; set; }
public int? prop3 { get; set; }
public decimal? prop4 { get; set; }
}
查看
@Html.LabelFor(m => m.prop3 )
@Html.DropDownListFor(m => m.prop3 , new SelectList(your items, "Id", "type"), "", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.prop3 )
答案 1 :(得分:0)
[RequiredIf("prop2!= null", ErrorMessageResourceName = "prop1")]
public int? prop1{ get; set; }
[RequiredIf("prop1> 0", ErrorMessageResourceName = "prop2")]
public decimal? prop2{ get; set; }
[RequiredIf("prop4!= null", ErrorMessageResourceName = "prop3")]
public int? prop3{ get; set; }
[RequiredIf("prop3> 0", ErrorMessageResourceName = "prop4")]
public decimal? prop4{ get; set; }