更新模型并向模型添加新对象

时间:2013-07-11 18:42:23

标签: c# asp.net-mvc entity-framework

我有一个实体如下:

class Project{
   public int Id {set;get;}
   ... some other props
   public virtual Image Image {set;get;}
}
控制器上的

我有以下内容:

       [HttpPost]
        public ActionResult Edit(Project project, HttpPostedFileBase file1)
        {
            if (ModelState.IsValid)
            {
                if (file1 != null)
                {
                    var path = FileUploadHelper.UploadFile(file1, Server.MapPath(ProjectImages));

                    var image = new Image { ImageName = file1.FileName, Path = path, ContentType = file1.ContentType };

                    var imageEntity = db.Images.Add(image);
                    db.SaveChanges();
                    project.MainImage = imageEntity;
                }
                else
                {
                    ModelState.AddModelError("FileEmpty", "You need to upload a file.");
                    return View(project);
                }

                db.Entry(project).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(project);
        }

问题在于,当我为此记录阅读项目时,我仍然看到旧图像。即:它没有更新给定项目实体的图像。

为什么会这样?

我可以从DB加载项目并为其分配值。但为什么这不起作用?我可以在不从db加载对象的情况下使其工作吗?

3 个答案:

答案 0 :(得分:0)

您的项目对象似乎未附加到上下文 试试这个

            if (file1 != null)
            {
                var path = FileUploadHelper.UploadFile(file1, Server.MapPath(ProjectImages));

                var image = new Image { ImageName = file1.FileName, Path = path, ContentType = file1.ContentType };
                db.Project.Attach(project);
                db.Images.Add(image);                    
                project.MainImage = image;
                context.Entry(project).State = EntityState.Modified;
                db.SaveChanges();
            }

在POST方法结束时删除它:

            db.Entry(project).State = EntityState.Modified;
            db.SaveChanges();

答案 1 :(得分:-2)

达斯,我之前已经处理过这个问题,这对于MVC来说是一个疯狂的怪癖。您正在使用post方法更改模型并将其返回到同一视图。如果不先清除值,它就不会将新值传递回视图。

ModelState.Remove("MainImage");
ModelState.SetValue("MainImage", imageEntity);

或者

ModelState.Clear();

然后完全重建模型。我知道这听起来很疯狂,但是,在那里,做到了,在这种情况下没有别的办法。

答案 2 :(得分:-2)

在MVC和浏览器中禁用自动缓存,以便每次都可以更新到最新版本。

您可以使用OutputCacheAttribute控制服务器和/或浏览器缓存,以控制控制器中的特定操作或所有操作。

禁用控制器中的所有操作:

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will be applied to all actions in MyController, unless those actions override with their own decoration
public class MyController : Controller
{
  // ... 
}

停用特定操作:

public class MyController : Controller
{
    [OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will disable caching for Index only
    public ActionResult Index()
    {
       return View();
    }
} 
相关问题