Chr*_*son 3 c# asp.net asp.net-mvc validationattribute
基本上我想弄清楚的是如何要求在视图中填写两个字段中的至少一个.
在我的视图中,我有两个名为ISBN和ISBN13的文本字段.用户填写哪一个并不重要,只要其中一个填写.
我不确定在这里做什么期望考虑编写一个自定义验证器,所以我想我先问.我会包含一些代码,但由于它只是两个简单的字段,我认为这种解释会更好.
您可以在控制器操作中进行手动验证.该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);
}
Run Code Online (Sandbox Code Playgroud)
有些人可能会说控制器不负责查询的验证.我认为控制器的职责是使Web请求适应域请求.因此,控制器可以具有验证逻辑.如果您没有域/业务层,那么这种考虑是没有意义的.
使用MVC Foolproof NuGet 包,然后您可以使用如下RequiredIf属性:
[RequiredIf("ISBN==\"\"")] // backslash is used for escaping the quotes
public string ISBN13 { get; set; }
[RequiredIf("ISBN13==\"\"")]
public string ISBN { get; set; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2762 次 |
| 最近记录: |