2013-04-02 92 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); 

}