您可以在视图中通过检查
$.validator
有效。由于默认情况下不会验证隐藏输入,因此还需要覆盖验证器。在后面添加以下内容
jquery-{version}.js
jquery.validate.js
和
jquery.validate.unobtrusive.js
脚本(但不在
$(document).ready()
<script>
// override validator to include hidden inputs
$.validator.setDefaults({
ignore: []
});
// validate form and display errors
$('form').valid();
</script>
请注意,您可能包括(比如)
<p id="error" style="display:none;">
包含数据无效的“常规”错误消息的标记,并使用
if ($('form').valid()) {
$('#error').show();
}
缺点是需要包含jQuery脚本,否则就不需要这些脚本。
另一种选择是使用在控制器中进行验证
TryValidateObject
ModelState
将显示在您的
ValidationMessageFor()
占位符。注意以下假设
csvRecords
机具
IList<T>
这样你就可以使用
for
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase csvFile)
{
// var csvRecords = do stuff to retrieve data from CSV file
var newUsersToCreate = new List<UserViewModel>();
for (int i = 0; i < csvRecords.Count; i++)
{
UserViewModel model = new UserViewModel
{
Name = csvRecords[i].Name,
....
};
newUsersToCreate.Add(model);
// validate the model and include the collection indexer
bool isValid = ValidateModel(model, i));
}
return View("ImportPreview", newUsersToCreate);
}
private bool ValidateModel(object model, int index)
{
var validationResults = new List<ValidationResult>();
var context = new ValidationContext(model);
if (!Validator.TryValidateObject(model, context, validationResults, true))
{
foreach (var error in validationResults)
{
string propertyName = $"[{index}].{error.MemberNames.First()}";
ModelState.AddModelError(propertyName, error.ErrorMessage);
}
return false;
}
return true;
}
控制器代码的优点是可以向视图模型中添加其他属性(例如
bool IsValid