MVC使用NULL更新值

时间:2014-08-10 17:12:54

标签: asp.net-mvc null viewmodel updatemodel

对于大多数MVC程序员来说,这可能非常简单,所以也许你可以帮助我。我在数据库中有一个名为Images的表,有九列。在我的UPDATE,我只有三个我想要搞乱(ImageName,ImagePath,CourseID)。在我使用UPDATE回发后,它将其他六列设置为NULL。我不确定如何在MVC中处理这个问题。:

Image table

Image table after UPDATE

我的ViewModel:

public class GalleryViewModel
{     
  public Image _image { get; set; }
}  

我的模特:

 public partial class Image
 {
    public int ImageID { get; set; }
    public string ImageName { get; set; }
    public string ImagePath { get; set; }
    public Nullable<int> CourseID { get; set; }
    public string UserId { get; set; }
    public Nullable<System.DateTime> CreateDate { get; set; }
    public string ImageType { get; set; }
    public string ImageSize { get; set; }
    public string FriendlyName { get; set; }

    public virtual Cours Cours { get; set; }
}

我的控制器:

   [HttpGet]
    public ActionResult UploadImageEdit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var model = new GalleryViewModel
        {
            _image = db.Images.Find(id),
        };
        return View(model);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UploadImageEdit(GalleryViewModel galleryViewModel)
    {
        if (ModelState.IsValid)
        {
            db.Entry(galleryViewModel._image).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("UploadImageIndex");
        }
        return View(galleryViewModel);
    }

1 个答案:

答案 0 :(得分:1)

在阅读其他示例并更熟悉ViewModel到控制器之后,我通过执行以下操作获得了UPDATE:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UploadImageEdit(int id, GalleryViewModel galleryViewModel)
    {
        if (ModelState.IsValid)
        {
            var imageContext = db.Images.Find(id);

            imageContext.FriendlyName = galleryViewModel._image.FriendlyName;
            db.Entry(imageContext).State = EntityState.Modified;
            db.SaveChanges();

            return RedirectToAction("UploadImageIndex");
        }
        return View(galleryViewModel);
    }

我希望这有助于其他人!