如何正确制作byte []字段必填字段?

rex*_*ror 4 .net c# asp.net-mvc entity-framework data-annotations

我需要byte[]在我的模型中验证 a ,Required但是每当我使用Data Annotation [Required]它时,它都不会做任何事情。即使我选择了一个文件,它也会输出错误消息。

细节:

模型:

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

   [Required]
   public string Name {get; set;}

   public byte[] Image {get; set;}

   [Required]
   public byte[] Template {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

看法:

<div class="editor-label">
   <%:Html.LabelFor(model => model.Image) %>
</div>
<div class="editor-field">
   <input type="file" id="file1" name="files" />
</div>
<div class="editor-label">
   <%:Html.Label("Template") %>
</div>
<div class="editor-field"> 
   <input type="file" id="file2" name="files"/>
</div>
<p>
   <input type="submit" value="Create" />
</p>
Run Code Online (Sandbox Code Playgroud)

我环顾了帖子并注意到人们使用自定义验证,但由于某种原因,当我尝试使用相同的 it 错误并缺少 ID 时,他们已将其用作HttpPostedFileBase文件类型而不是byte[]像我一样......即使模型声明了自己的 ID。

编辑:

上下文 -OnModelCreating添加Report

modelBuilder.Entity<Report>().Property(p => p.Image).HasColumnType("image");
modelBuilder.Entity<Report>().Property(p => p.Template).HasColumnType("image");
Run Code Online (Sandbox Code Playgroud)

请注意,由于错误,我不得不将其image作为。ColumnTypeByte array truncation to a length of 4000.

控制器:

public ActionResult Create(Report report, IEnumerable<HttpPostedFileBase> files)
    {

        if (ModelState.IsValid)
        {
            db.Configuration.ValidateOnSaveEnabled = false;

            if (files.ElementAt(0) != null && files.ElementAt(0).ContentLength > 0)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    files.ElementAt(0).InputStream.CopyTo(ms);
                    report.Image = ms.GetBuffer();
                }
            }

            if (files.ElementAt(1) != null && files.ElementAt(1).ContentLength > 0)
            {
                using (MemoryStream ms1 = new MemoryStream())
                {
                    files.ElementAt(1).InputStream.CopyTo(ms1);
                    report.Template = ms1.GetBuffer();
                }

            }
            db.Reports.Add(report);
            db.SaveChanges();

            //Temporary save method
            var tempID = 10000000 + report.ReportID;
            var fileName = tempID.ToString(); //current by-pass for name
            var path = Path.Combine(Server.MapPath("~/Content/Report/"), fileName);
            files.ElementAt(1).SaveAs(path);

            db.Configuration.ValidateOnSaveEnabled = true;
            return RedirectToAction("Index");
        }
Run Code Online (Sandbox Code Playgroud)

希望你能注意到我遗漏了什么。

Kyl*_*man 5

RequiredAttribute对空和检查一个空字符串。

public override bool IsValid(object value)
{
  if (value == null)
    return false;
  string str = value as string;
  if (str != null && !this.AllowEmptyStrings)
    return str.Trim().Length != 0;
  else
    return true;
}
Run Code Online (Sandbox Code Playgroud)

如果您的字节数组为空,这可以正常工作,但您可能还想检查一个空数组(没有看到您如何分配您的Template属性值,我只能猜测是这种情况)。您可以定义自己的必需属性来为您执行此检查。

public class RequiredCollectionAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
      bool isValid = base.IsValid(value);

      if(isValid)
      {
        ICollection collection = value as ICollection;
        if(collection != null)
        {
            isValid = collection.Count != 0;
        }
      }  
      return isValid;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在只需用我们的新属性替换Required您的属性上的属性。TemplateRequiredCollection

[RequiredCollection]
public byte[] Template {get; set;}
Run Code Online (Sandbox Code Playgroud)