我尝试对列表进行客户端验证。我希望列表中至少有一个项目。
我使用此处找到的解决方案: ViewModel validation for a List
正在调用ValidationAttribute,当列表为空或为null时它返回false,但表单仍在提交。
型号:
public class ProductsViewModel
{
UniformRepository repo;
public ProductsViewModel()
{
repo = new UniformRepository();
Products = new List<Product>();
ProductToEdit = new Product();
Divisions = repo.GetAllDivisions();
}
public List<Product> Products { get; set; }
public Product ProductToEdit { get; set; }
public Division SelectedDivision { get; set; }
public List<SelectListItem> DropDownVendors { get; set; }
public List<Division> Divisions { get; set; }
[EnsureOneElement(ErrorMessage = "At least one vendor is required")]
public List<string> Vendors { get; set; }
}
有问题的观点的一部分:
<div class="row top-buffer">
<div class="col-md-3 col-md-offset-1">
@Html.LabelFor(model => model.Vendors, new { @class = "GridLabel" })
</div>
<div class="col-md-3">
@(Html.Kendo().MultiSelectFor(model => model.Vendors)
.BindTo(Model.DropDownVendors)
.HtmlAttributes(new { @class = "form-control" }))
@Html.ValidationMessageFor(model => model.Vendors, "", new { @class = "text-danger" })
</div>
</div>
ValidationAttribute
public class EnsureOneElementAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var list = value as IList;
if (list != null)
{
return list.Count > 0;
}
return false;
}
}
感谢任何想法。