【问题标题】:ASP.NET MVC4 with Entity Framework not passing fields in Edit operation带有实体框架的 ASP.NET MVC4 未在编辑操作中传递字段
【发布时间】:2013-06-11 14:47:24
【问题描述】:

我正在开发一个小型 ASP.NET MVC4 Web 应用程序,它使用实体框架将该应用程序与我的数据库链接起来。我让 Visual Studio 2012 生成控制器和视图中的所有 CRUD 操作,除了编辑之外一切正常。

我生成的对象如下:

public partial class Post
{
    public Post()
    {
        this.Attachment = new HashSet<Attachment>();
    }

    [Display(AutoGenerateField = false)]
    public int post_id { get; set; } // This is the PK of my table
    public string title { get; set; }
    public string text { get; set; }
    [Display(AutoGenerateField = false)]
    public System.DateTime created { get; set; }
    [Display(AutoGenerateField = false)]
    public Nullable<System.DateTime> modified { get; set; }
    [Display(AutoGenerateField = false)]
    public string author { get; set; } // This is a FK from the "author" table

    public virtual ICollection<Attachment> Attachment { get; set; }
    public virtual Author Author1 { get; set; }
}

而Edit POST操作如下:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Post post)
{
    if (ModelState.IsValid)
    {
        post.modified = DateTime.Now;
        db.Entry(post).State = EntityState.Modified;
        db.SaveChanges(); // DbUpdateConcurrencyException thrown here
        return RedirectToAction("Index");
    }
    ViewBag.author = new SelectList(db.Author, "author1", "password", post.author);
    return View(post);
}

当我提交编辑后的帖子时,ASP.NET 吐出一个 DbUpdateConcurrencyException 说该操作影响了意外的行数 (0)。

调试的时候发现author、created、post_id都是null;他们都应该保持自己的价值观。

我该如何解决这个问题?

提前致谢。

【问题讨论】:

  • 您是从您的视图中发布的吗?您将它们设置为错误的自动生成字段,您应该将它们作为隐藏字段放在您的视图中,或者通过代码将它们设置在您的控制器中

标签: c# asp.net-mvc-4 visual-studio-2012 entity-framework-5


【解决方案1】:

在您的 Edit View() 上,您应该在隐藏字段中添加这些属性:

@Html.HiddenFor(m => m.post_id) etc.

这样它们将绑定在后期模型上,您可以在编辑方法中使用它们。

【讨论】:

  • 成功了。一旦我做了你发布的内容并删除了显示注释,一切都会顺利进行。谢谢。
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 2014-03-17
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
相关资源
最近更新 更多