大家好!
我在模型验证方面有点像菜鸟,我一直在尝试使用IValidatableObject接口验证Articles对象和上传的文件,但没有成功。
下面的类验证了Articles对象,但是我无法看到如何注入HttpPostedFileBase以允许我对其进行验证。这甚至可以使用这种方法吗?
我用来提交数据的表单包括enctype = multipart / form-data属性,因此它知道它的发布文件。
这是我试图验证的全班。这真的让我陷入困境,任何帮助将非常感激。
public class ArticlesModel : IValidatableObject
{
public Article Article { get; set; }
public IEnumerable<Category> Categories { get; set; }
public HttpPostedFileBase PostedFile { get; set; }
public ArticlesModel(){}
public ArticlesModel(Article article, IEnumerable<Category> categories)
{
this.Article = article;
this.Categories = categories;
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Article.CategoryID == 0)
{
yield return new ValidationResult("Please select a category.", new[] { "Article.Category"});
}
if (Article.Title == null)
{
yield return new ValidationResult("Please enter a title.", new[] { "Article.Title" });
}
if (Article.Content == null)
{
yield return new ValidationResult("Please enter some content.", new[] { "Article.Content" });
}
if (PostedFile == null)
{
yield return new ValidationResult("Please upload a file.", new[] { "Article.ImageFile" });
}
else
{
if (PostedFile.ContentLength > 1 * 1024 * 1024)
{
yield return new ValidationResult("Please upload a file 1Mb or less.", new[] { "Article.ImageFile" });
}
//Other file checking logic here please!!
}
}
}