我的控制器中有操作方法。如果照片附在表格中,我的方法可以正常工作。如果照片没有从编辑操作中的表单上传,我的方法是从数据库中删除最旧的照片。如果表格中没有附加最新文件,如何保存最旧的照片?
模型:
[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; }
}
控制器:
[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);
}