【问题标题】:How to update just some of properties in Edit action如何在编辑操作中仅更新一些属性
【发布时间】:2014-06-22 05:45:08
【问题描述】:

前言

我正在使用 MVC 5 开发一个项目。我们已经建立了我们的database,我们的model 就是从中创建的。然后,我们使用脚手架添加了ControllersViews。但是在视图中我们省略了一些属性(它们不应该显示给用户)。
问题
在像编辑这样的操作中,当我点击保存按钮(更新模型)时,我遇到了一个exception,我认为它需要我提供所有属性的值。

请告诉我如何只更新部分属性(显示在视图中)? 请注意,我需要一个尽可能通用的解决方案,以便能够在我在这个项目中的许多编辑操作中使用它(这确实是困难的部分)。
代码
以下是我认为与这个问题最相关的一些代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "AreaCode,Tels,Address")] Area area)
    {//Area has many more properties (defined as required in the database) and I just need to update
        //these : AreaCode,Tels,Address
    if (ModelState.IsValid)
    {
        db.Entry(area).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.Detector = new SelectList(db.Detectors, "DetectorCode", "detectorName", area.Detector);
    ViewBag.Grade = new SelectList(db.Grades, "Gradeid", "GradeName", area.Grade);
    return View(area);
}

SS

非常感谢以简单方式表达的答案。

【问题讨论】:

    标签: c# asp.net asp.net-mvc database asp.net-mvc-scaffolding


    【解决方案1】:

    从数据库中获取要更新的对象,并使用属性的旧值设置模型

    public ActionResult Edit([Bind(Include = "AreaCode,Tels,Address")] 区域区域) {

    YourDbContext _db= new YourDbContext();
    Area oldArea = _db.Areas.Where(x => x.ID == area.ID).FirstOrDefault();
    
    
      // Bind others properties marked with required from database 
       area.x = oldArea.x;
       area.y = oldArea.y;
    
    
    if (ModelState.IsValid)
    {
        db.Entry(area).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.Detector = new SelectList(db.Detectors, "DetectorCode", "detectorName", area.Detector);
    ViewBag.Grade = new SelectList(db.Grades, "Gradeid", "GradeName", area.Grade);
    return View(area);
    

    }

    【讨论】:

      猜你喜欢
      • 2020-04-02
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2021-10-21
      相关资源
      最近更新 更多