2013-06-11 16 views
0

我正在使用實體框架將小應用程序與我的數據庫鏈接起來,從事一個小型ASP.NET MVC4 Web應用程序。我讓Visual Studio 2012在控制器和視圖中生成所有CRUD操作,並且除編輯以外,一切正常。帶實體框架的ASP.NET MVC4未在編輯操作中傳遞字段

我生成的對象如下:

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; } 
} 

與編輯後的操作如下:

[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)。

當調試時,我發現作者,創建和post_id爲空;他們都應該保持自己的價值觀。

我該如何解決這個問題?

在此先感謝。

+0

你從視圖中發佈它們嗎?您將它們設置爲虛假自動生成的字段,您應該將它們作爲隱藏字段放在您的視圖中,或者通過代碼 – freshbm

回答

1

在你編輯視圖(),你應該在隱藏字段中添加這些屬性:

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

這樣,他們就在哪裏交模型綁定,你可以在你的編輯方式使用它們。

+0

將它們設置在您的控制器中。一旦我做了你發佈的內容並刪除了顯示註釋,那麼所有內容都會順利進行。謝謝。 –