Asp.net mvc 列表的自定义ValidationAttribute不会阻止表单提交
我正在尝试对列表进行客户端验证。我希望列表中至少有一项 我使用的解决方案如下: 正在调用ValidationAttribute,当列表为空或null,但表单仍在提交时,它将返回false 型号:Asp.net mvc 列表的自定义ValidationAttribute不会阻止表单提交,asp.net-mvc,razor,kendo-ui,Asp.net Mvc,Razor,Kendo Ui,我正在尝试对列表进行客户端验证。我希望列表中至少有一项 我使用的解决方案如下: 正在调用ValidationAttribute,当列表为空或null,但表单仍在提交时,它将返回false 型号: public class ProductsViewModel { UniformRepository repo; public ProductsViewModel() { repo = new UniformRepository(); Pro
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; }
}
谢谢您的建议。您的EnsureNeeelementAttribute是服务器端代码,没有与客户端等效的代码,因此表单会被提交,因为客户端中没有任何东西可以阻止它。像Required work这样的开箱即用属性是因为它们生成客户端属性,比如“data val Required”,客户端可以理解并强制执行这些属性。您需要自己实现相应的客户端强制。请参阅(以及许多其他内容)。您的属性需要实现
iclientvalidable
,并且您需要编写脚本将规则添加到“$.validator”。参考
<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>
public class EnsureOneElementAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var list = value as IList;
if (list != null)
{
return list.Count > 0;
}
return false;
}
}