ASP.NET MVC中的验证框架默认情况下在提交表单时验证所有行。但是,有时可能只想验证表单中的单个行,而不想验证所有行。以下是一种实现此功能的解决方法,该解决方法基于表单提交时不传递某些字段的方法:
@using (Html.BeginForm("YourAction", "YourController")) {
@Html.TextBoxFor(m => m.Property1, new { @class = "form-control", data_val = "true", data_val_required = "Field1 is required." })
@Html.HiddenFor(m => m.Property2, new { data_val = "false" }) // Excluded Property
@Html.TextBoxFor(m => m.Property3, new { @class = "form-control", data_val = "true", data_val_required = "Field3 is required." })
}
在上面的示例中,Property2表示要忽略验证的字段,并将其值设置为data_val ="false"
。
TryValidateModel
方法来验证表单数据。[HttpPost]
public ActionResult YourAction(YourModel model) {
ModelState.Remove("Property2"); // Exclude the ignored Property
// Validate only the passed fields
bool isValid = TryValidateModel(model, "", ModelState.Keys
.Where(k => !k.Contains("Property2")));
if (isValid) {
// Your code here
}
return View();
}
在上面的示例中,ModelState.Remove("Property2")
移除要忽略的字段,TryValidateModel
方法ModelState.Keys.Where(k => !k.Contains("Property2")))
用于仅验证要提交的字段,如果验证通过,则可以执行其他代码。
需要注意的是,在上面的示例中,如果要移除多个字段,则可以将它们添加到一个字符串数组中,并使用Contains()
扩展方法检查字段名称。