我的对象中有 ImageUrl。如果实体在没有参考图片的情况下进行编辑,则字段重置。如何正确更新对象?
public ActionResult Index()
{
var items = db.Employes;
return View(items);
}
public ActionResult Edit(int id = 0)
{
var item = (id != 0) ? db.Employes.Find(id) : new Employee();
return View(item );
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(int id = 0, FormCollection formValues = null, Employee item = null)
{
if (id == 0)
db.Employes.Add(item);
else
{
item = db.Employes.Find(id);
UpdateModel(item);
}
Helpers.FileSave("Image", item, formValues);
db.SaveChanges();
return RedirectToAction("Index");
}
更新1:
从 updateModel 中排除字段后,我无法添加新图像:
if (id == 0)
db.Employes.Add(item);
else
{
item = db.Employes.Find(id);
if (formValues["Image"] != null)
{
UpdateModel(item);
Helpers.FileSave("Image", item, formValues);
}
else
{
string[] excludeProperties = { "Image" };
UpdateModel(item, null, null, excludeProperties);
}
}