I have action method in my controller. If photo is attached in form my method work fine. If photo don’t upload from form in Edit action my method to removes oldest photo from database. How to save oldest photo if in form not attached newest file?
Model:
[DisplayColumn("LastName")]
public class Driver
{
[Key]
public int Id { get; set; }
[Display(Name="Full Name")]
[DataType(DataType.Text)]
public string FullName
{
get { return string.Concat(FirstName.Substring(0, 1), ".", LastName);}
}
[Required]
[Display(Name = "First Name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[Display(Name = "Middle Name")]
[DataType(DataType.Text)]
public string MiddleName { get; set; }
[Required]
[Display(Name = "Last Name")]
[DataType(DataType.Text)]
public string LastName { get; set; }
public byte[] DriverPhoto { get; set; }
}
Controller:
[HttpPost]
public ActionResult Edit(Driver driver, HttpPostedFileBase fileUpload)
{
if(fileUpload != null)
{
var binaryReader = new BinaryReader(fileUpload.InputStream);
driver.DriverPhoto = binaryReader.ReadBytes(fileUpload.ContentLength);
}
if (ModelState.IsValid)
{
db.Entry(driver).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(driver);
}
I modified code my controller this:
Now my controller works the way I wanted, but I’m not sure about the correctness of the solution.
Thanks for help me.