I need to check byte[] in my model as Required , but whenever I use Data Annotation [Required] it will do nothing. Even if I select a file, it gives an error message.
More details:
Model:
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;} }
View:
<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>
I looked through the messages and noticed that people use special checking, but they used HttpPostedFileBase as file types instead of byte[] , like me, for some reason, when I try to use the same errors with an missing ID for it ... Despite that the model has its own identifier.
EDIT:
Context - OnModelCreating Add- OnModelCreating for Report
modelBuilder.Entity<Report>().Property(p => p.Image).HasColumnType("image"); modelBuilder.Entity<Report>().Property(p => p.Template).HasColumnType("image");
Please note that I had to set image as ColumnType due to Byte array truncation to a length of 4000. error.
Controller:
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"); }
I hope you notice what I am missing.
source share