基本上我想弄清楚的是如何要求在 View 中至少填写两个字段之一。
在我的 View 中,我有两个文本字段,分别称为 ISBN 和 ISBN13。用户填写哪一项都没有关系,只要其中一项被填写即可。
我不确定在这里要做什么才能考虑编写自定义验证器,所以我想我会先问一下。我会包含一些代码,但由于它只是两个简单的字段,我认为这个解释会更好。
最佳答案
您可以在 Controller 操作中进行手动验证。 AddModelError
方法将帮助您使用验证堆栈。
[HttpPost]
public ActionResult Edit(EditModel model)
{
if (string.IsNullOrEmpty(model.ISBN) && string.IsNullOrEmpty(model.ISBN13))
{
var validationMessage = "Please provide ISBN or ISBN13.";
this.ModelState.AddModelError("ISBN", validationMessage);
this.ModelState.AddModelError("ISBN13", validationMessage);
}
if (!string.IsNullOrEmpty(model.ISBN) && !string.IsNullOrEmpty(model.ISBN13))
{
var validationMessage = "Please provide either the ISBN or the ISBN13.";
this.ModelState.AddModelError("ISBN", validationMessage);
this.ModelState.AddModelError("ISBN13", validationMessage);
}
if (this.ModelState.IsValid)
{
// do something with the model
}
return this.View(model);
}
有些人可能会说, Controller 不负责对查询进行验证。我认为 Controller 的职责是将网络请求适配为域请求。因此, Controller 可以有验证逻辑。如果您没有域/业务层,这种考虑就没有意义。
关于c# - 需要一个或另一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43427335/