2012-04-05 134 views
-1

我正在做一個MVC 3應用程序。我正在使用Entity framwork數據庫方法的第一種方法。所以所有的代碼都是自動生成的。但問題是當我點擊「編輯」,「詳細信息」和「刪除」鏈接,我得到這個錯誤。MVC3自動生成的代碼錯誤

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'Fin_trial_06.Controllers.AuthorController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. 
Parameter name: parameters. 

我的控制器代碼是:

public ActionResult Details(int? id) 
    { 
     Author authors = _entities.Authors.Single(n => n.Author_ID == id); 
     return View(authors); 
    } 

public ActionResult Edit(int id) 
    { 
     return View(_entities.Authors.Find(id)); 
    } 


    // POST: /Author/Edit/ 

    [AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult Edit(int id, Author aut) 
    { 
     if (id == null) 
      return View("AuthorNotFound"); 
     try 
     { 
      _entities.Entry(aut).State = EntityState.Modified; 
      _entities.SaveChanges(); 

      TempData["Message"] = "You have successfully Editied Author"; 
      return RedirectToAction("Index"); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 


public ActionResult Delete(int id) 
    { 
     return View(_entities.Authors.Find(id)); 
    } 


    // POST: /Author/Delete/5 

    [HttpPost] 
    public ActionResult Delete(int id, Author aut) 
    { 
     try 
     { 

      _entities.Entry(aut).State = EntityState.Deleted; 
      _entities.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 

幫助嗎?

+1

你能告訴我們你的看法嗎? – mattytommo 2012-04-05 13:05:08

回答

0

好,消息似乎很清楚

[AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult Edit(int id, Author aut) 
    { 
     if (id == null) 

如果無法進入活動ID == NULL。

小的後果:

if (id == null) 

是沒用的

解決方案: 無論您說的id是

int ? 

,或者你不要忘了把一個隱藏字段爲您編輯視圖中的編號

0

在這個m中放置一個斷點方法來查看一個id是否被傳遞給你的編輯函數。如果沒有,那麼你的觀點是錯誤的,而不是通過你想編輯的項目的ID。如果你發佈你的視圖代碼,我可以告訴你它失敗的地方。

+0

@Raphael使參數無效是不會解決他的問題。如果他將一個空id傳遞給編輯函數,該函數將如何知道要編輯哪個項目? – JCisar 2012-04-05 13:11:34