【问题标题】:ASP.NET MVC Validation Architecture for DB Validated valuesDB Validated 值的 ASP.NET MVC 验证体系结构
【发布时间】:2011-09-01 09:32:54
【问题描述】:

假设我有这样的课程

public class Blog{
  [Key]
  public int ID{get;set;}

  //these can only be tags that are in the tags db table
  IEnumerable<string> Tags{get;set;}

  //validation pseudocode to illustrate issue
  public bool IsValid() {

    //this is my issue-- how do i get my db context/repository 
    //into my validation logic for this class? i need it
    var goodTags=db.Tags.Select(i=>i.Name);

    //if this tag isn't a "goodTag", then this shouldnt validate
    Tags.ForEach(i=> {

       if(!goodTags.Contains(i))
          return false;
    });
 }
 }

如何在不将数据访问逻辑放入模型中的情况下验证标签中包含的字符串是否在标签数据库表中?我正在使用 MVC3。你是怎么做到的?

谢谢!

【问题讨论】:

    标签: asp.net validation asp.net-mvc-3 architecture


    【解决方案1】:

    使用 IInvalidatableObject 进行自我验证,如下所示:

    public Class Blog : IValidatableObject
    {
          [Key]
          public int Id {get; set;}
    
          public ICollection<string> Tags {get; set;}
    
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if(!Tags.Contains("testString"))
            {
                  yield return new ValidationResult("Not a valid tag.", new [] {"Tags"});
            }
        }
    }  
    

    【讨论】:

    • 我添加了更多代码来显示真正的问题——将数据上下文获取到 IValidateableObject 的模型中。非常感谢您的回答,非常感谢。
    • 您的存储库架构是什么?实体?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2010-12-15
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    相关资源
    最近更新 更多