I know tis is not a new question, but I've looked at all the topics related and coudn't find my answer. My proble is that I have stored image data into sql db, but can't display them on edits or index (MVC 5). Can you please help me, thanks in advance. Here are my codes:
CONTROLLER
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "DrvId,FullName,Address,Postcode,Contact,Email,County,File,Date")] DriverReg driverReg, HttpPostedFileBase[] files)
{
if (ModelState.IsValid)
{
try
{
/*Lopp for multiple files*/
foreach (HttpPostedFileBase file in files)
{
/*Geting the file name*/
string filename = System.IO.Path.GetFileName(file.FileName);
/*Saving the file in server folder*/
file.SaveAs(Server.MapPath("~/Content/UploadedFiles/" + filename));
string filepathtosave = "UploadedFiles/" + filename;
/*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
}
ViewBag.Message = "File Uploaded successfully.";
}
catch
{
ViewBag.Message = "Error while uploading the files.";
}
db.DriversReg.Add(driverReg);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(driverReg);
}
MODEL
namespace HopeRemovalsFinal.Models
{
public class DriverReg
{
[Key]
public int DrvId { get; set; }
public string FullName { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public string County { get; set; }
[DataType(DataType.Upload)]
[Display(Name ="Upload File")]
[Required(ErrorMessage ="Please choose file to upload")]
public string File { get; set; }
// public string FileName { get; set; }
public DateTime Date { get; set; }
}
public class DriverDbContext : DbContext
{
public DriverDbContext()
: base("VanRemovals")
{
}
public static DriverDbContext Create()
{
return new DriverDbContext();
}
public DbSet<DriverReg> DriversReg { get; set; }
}
}
DETAILS VIEW
<dt>
@Html.DisplayNameFor(model => model.File)
</dt>
<dd>
@Html.DisplayFor(model => model.File)
</dd>
DATABASE RESULTS
Create New
FullName Address Postcode Contact Email County Upload File Date
John manchester M32 7DD 098764587 [email protected] Lancashire uk_map.png 19/04/2016 00:00:00 Edit | Details | Delete
The UploadedFiles folder is empty but the file has been saved on db. Thanks for your help.