I'm attempting client side validation of a list. I want at least one item to be in the list.
I'm using the solution found here: ViewModel validation for a List
The ValidationAttribute is being called, and it is returning false when the list is empty or null, but the form is still submitting.
Model:
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; }
}
part of the View in question:
<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;
}
}
Thanks for any ideas.