2013-04-02 91 views
0

我在我的控制上述兩措施:錯誤acessing控制器.... Asp.net MVC 4

public ActionResult Admin() 
    { 
     var aux=db.UserMessages.ToList(); 

     return View(aux);   

    } 

    public ActionResult Admin(int id) 
    { 
     var aux = db.UserMessages.ToList(); 

     return View(aux); 

    } 

但是,當我嘗試訪問「本地主機/懷疑/管理員」我收到一個消息,說它不明白爲什麼...因爲如果我沒有在網址中的ID,它應該調用第一個動作沒有ID參數

+0

您的路線是如何定義的? – MilkyWayJoe

+0

請發佈錯誤 –

回答

2

不可能有相同的控制器都與同一個動詞接近2點的操作使用相同的名稱(在你的情況GET)。您必須重命名其中一個操作,或者使用HttpPost屬性對其進行修飾,使其僅對POST請求可訪問。顯然這不是你想要的,所以我想你將不得不重新命名第二個動作。

2

除非你指定ActionName屬性,這兩個動作將被發現時指定「管理員」操作。將方法與動作名稱匹配時,不會考慮參數。

您還可以使用HttpGet/HttpPost屬性指定一個用於GET,另一個用於POST。

[ActionName("AdminById")] 
public ActionResult Admin(int id) 

並在路由中指定「AdminById」,當路徑包含id。

0

當用戶查看頁面時,這是一個GET請求,當用戶提交表單時,通常是POST請求。 HttpGetHttpPost限制一個操作方法,以便該方法僅處理相應的請求。

[HttpGet] 
    public ActionResult Admin() 
    { 
     var aux=db.UserMessages.ToList(); 

     return View(aux);   

    } 

    [HttpPost] 
    public ActionResult Admin(int id) 
    { 
     var aux = db.UserMessages.ToList(); 

     return View(aux); 

    } 

在你的情況,如果你想有一個get請求到第二個方法,你最好重命名你的方法。

0
As you have define two action method with same name,it get confuse about which method to call. 
so of you put request first time and in controller you have two method with same name than it will show error like you are currently getting due to it try to find method with attribute HttpGet,but you have not mention that attribute on action method,now when you post your form at that time it will try to find method with HttpPost attribute and run that method,so you have to specify this two attribute on same method name 
    Try this 
    [HttpGet] 
    public ActionResult Admin() 
     { 
      var aux=db.UserMessages.ToList(); 

      return View(aux);   

     } 
    [HttpPost] 
     public ActionResult Admin(int id) 
     { 
      var aux = db.UserMessages.ToList(); 

      return View(aux); 

     } 
0

在ASP.NET MVC中,不能有兩個動作具有相同的名稱和相同的動詞。你可以像這樣編寫代碼來保持代碼的可讀性。

private ActionResult Admin() 
{ 
    var aux=db.UserMessages.ToList(); 
    return View(aux);   

} 

public ActionResult Admin(int id = 0) 
{ 
    if (id == 0) 
     return Admin(); 

    var aux = db.UserMessages.ToList(); 
    return View(aux); 

}