I need to validate a byte[] in my model as Required but whenever I use Data Annotation [Required] on it, it won’t do anything. Even if i choose a file it outputs error message.
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’ve looked around the posts and notice people use custom validation but they have used HttpPostedFileBase as types of files instead of byte[] like me, for some reason when I try to use the same it errors with a missing ID for it… Even though the model has it’s own ID declared.
EDIT:
Context – OnModelCreating additions for Report
modelBuilder.Entity<Report>().Property(p => p.Image).HasColumnType("image");
modelBuilder.Entity<Report>().Property(p => p.Template).HasColumnType("image");
note that i had to put image as ColumnType because of 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");
}
Hopefully you may notice what I’m missing.
I’ve altered my
Createmethod, and this is what I’ve come up with. Seems to work fine, but…