Reputation: 2697
I have ImageUrl in my object. If the entity edited without reference to picture, it's field reset. How I can correctly update object?
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");
}
upd1:
after excludind field from updateModel, I can't add new images:
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);
}
}
Upvotes: 0
Views: 1055
Reputation: 8199
First don't exclude properties second,In your else part of updated code add the following line
item.Image =formValues["Image"]
then call the update model
Upvotes: 1
Reputation: 2824
You should use the excludeProperties and includeProperties when calling UpdateModel.
In short...
string[] includeProperties = { “Name”, “Description”, “Active” };
UpdateModel(myModelView, includeProperties);
Upvotes: 2