I'm trying to upload files in my application. I've used HttpPostedFileBase
in my model and a byte[]
array but don't know why this error is showing when i'm running my application. Below I've also uploaded the image
of the error that is showing when running the app.
The error that is showing is:
One or more validation errors were detected during model generation:
AdSite.Models.HttpPostedFileBase: :
EntityType 'HttpPostedFileBase' has no key defined. Define the key for this EntityType.
HttpPostedFileBases: EntityType: EntitySet 'HttpPostedFileBases' is based on type 'HttpPostedFileBase' that has no keys defined.`
My Model:
public class Album
{
[Key]
public int Id { get; set; }
public string ProductTitle { get; set; }
public string Description { get; set; }
public string ImageFileName { get; set; }
public int ImageSize { get; set; }
public byte[] ImageData { get; set; }
[Required(ErrorMessage="Please select image file.")]
public HttpPostedFileBase File { get; set; }
}
My controller code:
public ActionResult Upload([Bind(Include = "Id,ProductTitle,Description,ImageFileName,ImageData,File,ImageSize")]Album album)
{
if (ModelState.IsValid)
{
// album.ImageFileName = album.File.FileName;
// album.ImageSize = album.File.ContentLength;
byte[] data = new byte[album.File.InputStream.Length];
album.File.InputStream.Read(data, 0, data.Length);
album.ImageData = data;
var db = new AlbumContext();
db.Albums.Add(album);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(album);
}
My View code:
<div class="form-group">
<label class="control-label col-md-2">Select Image:</label>
<div class="col-md-10">
@Html.TextBoxFor(model=>model.File, new { type="file"})
@Html.ValidationMessage("CustomError")
</div>
</div>
File
property is defined in theModel class
. it is of typeHttpPostedFileBase File
. You can see my model class here. – smk pobon Dec 8 '16 at 12:50public HttpPostedFileBase File { get; set; }
from your data model (its a complex object and cannot be stored in a database column). You editing data so use a view model and the view model will contain that property (and not thepublic byte[] ImageData { get; set; }
property - What is ViewModel in MVC? – Stephen Muecke Dec 9 '16 at 0:42