Getting error when creating ImagesController in MVC 4
-
27-10-2019 - |
Question
I'm trying to create an ImagesController in MVC4 like this
But I keep getting this error.
Had no problem creating controller for PeopleController using this class
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual IEnumerable<Affair> Affairs { get; set; }
}
Solution
The problem is with your File
property on the Image
class. Because EntityFramework won't understand the type HttpPostedFileBase
and can't store it in the DB and the controller generator is smart enough to check this. Altough the error message doesn't tell you what is the problem. To fix this you should rewrite your property to use a byte array:
public class Image
{
...
public byte[] File { get; set; }
}
And then the controller generation should work. And you can add your own image upload action, something like this:
[HttpPost]
public ActionResult Upload(Image image, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
db.Entry(image).State = EntityState.Modified;
image.File = new byte[file.ContentLength];
file.InputStream.Read(image.File, 0, file.ContentLength);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(image);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow