0

I have an MVC website and want to add an image to my model and display it in my view.

Currently, this is what my model looks like.

Model:

public class EventModel
{
    public string Title { get; set; }

    public string Location { get; set; }

    public byte[] EventLogo { get; set; }

    public string Description { get; set; }
}

For now, I have saved an image in my project under Content/Images/Logo-1.jpeg

I have not much knowledge on how I can save a image path to an array of byte. I suppose I would have to convert it first. Or is there an alternative data type i can use to save an image. Please advise.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user1781232
  • 659
  • 4
  • 13
  • 29
  • `"save a image path to an array of byte"` - An image's *data* would be a byte array. An image's *path* would be a string. Which are you trying to use? – David Mar 15 '15 at 13:48
  • @David Lets say you give the functionality to the users to upload an image. What data type will you use to store it? The image will be stored and retrieved from the database. But for the purpose of testing, the image is stored in my project. – user1781232 Mar 15 '15 at 13:59
  • in db you will need ``varbinary`` – Ehsan Sajjad Mar 15 '15 at 14:04

1 Answers1

0

You can save image path in database and then on getting display image from that path. Add a stribg property in Model for image path:

public string EventLogo { get; set; }

You can refer to this post(ASP.NET MVC 4 C# HttpPostedFileBase, How do I Store File) where I explained it well.

Community
  • 1
  • 1
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • The link to the answer you've provided is quite complicated. The user will be able to upload an image, the image will be stored and retrieved from the database and displayed in the view. Is storing it as a string the right way to do? – user1781232 Mar 15 '15 at 14:02
  • so you want to save image as `byte[]` in database – Ehsan Sajjad Mar 15 '15 at 14:03
  • From what I have searched online, it is stored as a byte. So Yes. Unless there is a simpler way of achieving this? – user1781232 Mar 15 '15 at 14:05
  • What I used to do is just save image path on which it is saved on server and fetch it when needed from the path, it's simple than storing image in db – Ehsan Sajjad Mar 15 '15 at 14:07
  • It might be simple but bear in mind it will be hard to maintain, if lets say, I have hundreds of images. So. it will be best if it is saved in the database against its other information – user1781232 Mar 15 '15 at 14:09
  • Its on choice my choice is always to save file path – Ehsan Sajjad Mar 15 '15 at 14:15
  • 1
    If you are putting image files in a SQL Server database you should reconsider your design. SQL Server isn't a document store. – Ray Suelzer Mar 15 '15 at 15:04