Error Message:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I want to get Image Url from database if fileupload has null value(not change).
I mean if i change smallImage and not change LargeImage,then it should get largeImage value from DB.
[HttpPost]
public ActionResult Edit(Blog blog, HttpPostedFileBase smallImage, HttpPostedFileBase largeImage)
{
if (ModelState.IsValid)
{
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength + "_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
else
{
blog.SmallImage = db.Blogs.Find(blog.ID).SmallImage;
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" + largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), largeImage.ContentLength + "_" + largeImage.FileName);
largeImage.SaveAs(filepath);
}
else
{
blog.LargeImage = db.Blogs.Find(blog.ID).LargeImage;
}
blog.PostDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
db.Entry(blog).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(blog);
}
Thank you.
You are both loading a copy of the blog
and attaching another with the same id to the context
meaning you have 2 copies of the same blog in the context (not allowed).
I’d recommend the replacing the one posted back with a viewmodel instead, something like