c# - 需要一个或另一个字段

标签 c# asp.net asp.net-mvc validationattribute

基本上我想弄清楚的是如何要求在 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/

相关文章:

c# - 使用jquery在ajax的回调中调用ajax

asp.net - WiX(Votive)项目引用收获(HEAT)一个 ASP.Net Web 应用程序

asp.net - 为什么 Content-Disposition header 在 IE 8 中不起作用?

ASP.NET MVC - Wordpress 风格的 URL

c# - 如何进行在其安装的程序中输入的设置?

c# - C#/ASP.NET 中的服务器端打印

c# - 有没有办法以编程方式绑定(bind)到 InputBinding Command 属性?

asp.net-mvc - 从母版页调用局部 View 时出现 ASP.NET MVC 堆栈溢出异常

c# - LINQ Group 通过跨多个表/类执行连接

c# - (NugetPackage)AdvancedDataGridView 排序/过滤列表