1

我的控制器中有操作方法。如果照片附在表格中,我的方法可以正常工作。如果照片没有从编辑操作中的表单上传,我的方法是从数据库中删除最旧的照片。如果表格中没有附加最新文件,如何保存最旧的照片?

模型:

[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);
    }
4

1 回答 1

1

我修改了我的控制器代码:

        [HttpPost]
    public ActionResult Edit(Driver driver, HttpPostedFileBase fileUpload)
    {
        if (fileUpload != null)
        {
            if (fileUpload.ContentType.ToLower() == "image/jpeg")
            {
                var binaryReader = new BinaryReader(fileUpload.InputStream);
                driver.DriverPhoto = binaryReader.ReadBytes(fileUpload.ContentLength);
            }
            else
            {
                ModelState.AddModelError("DriverPhoto","Illustrations should be uploaded in JPEG format.");
            }
    }

        if (ModelState.IsValid)
        {
            var entry = _db.Entry(driver);

            entry.State = EntityState.Modified;

            if (fileUpload == null)
            {
                entry.Property(t => t.DriverPhoto).IsModified = false;
            }

            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(driver);
    }

现在我的控制器按我想要的方式工作,但我不确定解决方案的正确性。

谢谢你帮助我。

于 2012-11-07T02:25:44.043 回答