Reputation: 279
I'm new in ASP.Net MVC and I'm working with an image column in my database. My question is how to retrieve image path from controller and send to HttpPostedFileBase image model? I'm getting the error in my code telling me that in Image = row.Image
cannot implicitly convert type 'string' to 'system.web.httppostedfilebase'
Here's my code:
Controller
public ActionResult CategoryForm(int? Id, int CategoryGroupId)
{
if (Id != null)
{
model = (from row in db.Categories
where row.Id == Id
select new NewCategoryViewModel
{
Id = row.Id,
CategoryGroupId = CategoryGroupId,
Name = row.Name,
Description = row.Description,
Image = row.Image,
Status = row.Status,
isMain = row.isMain
}).Single();
}
return PartialView("_CategoryFormPartialView", model);
}
Model
public class NewCategoryViewModel
{
public int Id { get; set; }
public int CategoryGroupId { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public HttpPostedFileBase Image { get; set; }
[Required]
public bool Status { get; set; }
[Required]
[Display (Name = "Display as main category?")]
public bool isMain { get; set; }
}
Thanks for helping me.
Upvotes: 0
Views: 796
Reputation: 51
First of all, I highly recommend you to not store images in your DB. It's very innefficient and the performance of your DB will decrease drastically. What I recommend is to upload the image to the server and save the reference in your database. Here's a link of a class I have to upload images to the server saved in date structure folder [YYYY/MM/DD].
Also, If the DB is returning a string and not a byte array, maybe you are saving the file name and not the file. I recommend reading this post just to confirm that you are saving the file.
The image from the database is not type HttpPostedFileBase. You need to convert the file.
If you are using the Image Field of SQL Server you need to use a byte array and convert the image to MemoryStream.
Model:
public byte[] Image { get; set; }
Controller:
Image = ConvertToImage(row.Image),
private HttpPostedFileBase ConvertToImage(byte[] image)
{
System.IO.File.ReadAllBytes(image);
return(HttpPostedFileBase)new MemoryPostedFile(bytes);
}
Upvotes: 1