Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用数据批注进行模型验证的错误消息_C#_Asp.net Mvc_Validation_Annotations_Data Annotations - Fatal编程技术网

C# 使用数据批注进行模型验证的错误消息

C# 使用数据批注进行模型验证的错误消息,c#,asp.net-mvc,validation,annotations,data-annotations,C#,Asp.net Mvc,Validation,Annotations,Data Annotations,鉴于以下类别: using System.ComponentModel.DataAnnotations; public class Book{ public Contact PrimaryContact{get; set;} public Contact SecondaryContact{get; set;} [Required(ErrorMessage="Book name is required")] public string Name{get; set;} }

鉴于以下类别:

using System.ComponentModel.DataAnnotations;

public class Book{
   public Contact PrimaryContact{get; set;}
   public Contact SecondaryContact{get; set;}

   [Required(ErrorMessage="Book name is required")]
   public string Name{get; set;}
}
public class Contact{
    [Required(ErrorMessage="Name is required")]
    public string Name{get; set;}
}
是否有一种干净的方法可以使用
DataAnnotations
Book
中的
Contact
的每个实例提供不同的错误消息?例如,如果
PrimaryContact
实例中缺少名称,则错误将显示为“PrimaryContact name is required”


我目前的解决方案是创建一个验证服务,检查模型状态是否存在字段错误,然后删除所述错误,并使用我喜欢的特定语言将其添加回去。

这是我所知道的唯一方法,但这还远远不够干净。它涉及使用子类化和元数据类来“覆盖”错误消息

public class Book
{
    public PrimaryContact PrimaryContact { get; set; }
    public SecondaryContact SecondaryContact { get; set; }

    [Required(ErrorMessage = "Book name is required")]
    public string Name { get; set; }
}

public class Contact
{
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }
}

[MetadataType(typeof(PrimaryContactMD))]
public class PrimaryContact : Contact
{
    class PrimaryContactMD
    {
        [Required(ErrorMessage = "Primary Contact Name is required")]
        public string Name { get; set; }
    }
}

[MetadataType(typeof(SecondaryContactMD))]
public class SecondaryContact : Contact
{
    class SecondaryContactMD
    {
        [Required(ErrorMessage = "Secondary Contact Name is required")]
        public string Name { get; set; }
    }
}

我也在寻找这个问题的答案,到目前为止,如果您在错误消息中执行类似于:“{0}联系人名称是必需的”的操作,它将自动替换变量的名称。我想有一种方法可以显式地使用此功能。

您可能希望查看对此类属性使用
CustomValidation
属性,而不是依赖
Required
属性

CustomValidation
将允许您根据正在验证的属性更精确地定制验证消息。我使用了
context.DisplayName
动态显示正在验证的属性的名称,只是为了简洁,但这可以根据您的需要进一步定制

如果需要进一步定制,您可以为每个属性编写不同的
CustomValidation
处理程序,而不是像我在代码示例中所做的那样重复使用相同的处理程序

using System.ComponentModel.DataAnnotations;

public class Book {
    [CustomValidation(typeof(Book), "ValidateContact")]
    public Contact PrimaryContact { get; set; }

    [CustomValidation(typeof(Book), "ValidateContact")]
    public Contact SecondaryContact { get; set; }

    [Required(ErrorMessage = "Book name is required")]
    public string Name { get; set; }

    public static ValidationResult ValidateContact(Contact contact, ValidationContext context) {
        ValidationResult result = null;

        if (contact == null) {
            result = new ValidationResult($"{context.DisplayName} is required.");
        } else if (string.IsNullOrWhiteSpace(contact.Name)) {
            result = new ValidationResult($"{context.DisplayName} name is required.");
        }

        return result;
    }
}

public class Contact {
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }
}
下面用c#编写的代码用于格式化数据注释错误,并在单个字符串中以追加格式格式化

  public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                if (actionContext.ModelState.IsValid) return;
                string errors = actionContext.ModelState.SelectMany(state => state.Value.Errors).Aggregate("", (current, error) => current + (error.ErrorMessage + ". "));
            }
        }
    }

请不要只发布代码作为答案,还要解释代码的作用以及它是如何解决问题的。带有解释的答案通常更有帮助,质量更好,更容易吸引选票