错误访问控制器.... Asp.net mvc 4

时间:2013-04-02 05:49:38

标签: c# asp.net-mvc 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);

    }

但是当我尝试访问“localhost / Doubt / Admin”时,我收到一条消息,说它含糊不清......我不明白为什么会这样...因为如果我在Url中没有id,它应该调用没有id参数的第一个Action

5 个答案:

答案 0 :(得分:2)

除非您指定ActionName属性,否则在指定“管理”操作时将找到这两项操作。将方法与操作名称匹配时,不会考虑参数。

您还可以使用HttpGet / HttpPost属性指定一个用于GET,另一个用于POST。

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

当路径包含id时,在路由中指定“AdminById”。

答案 1 :(得分:2)

在同一个控制器上有两个具有相同名称的动作是不可能使用相同的动词访问的(在您的情况下为GET)。您必须重命名2个操作中的一个,或者使用HttpPost属性对其进行修饰,使其仅对POST请求可访问。显然这不是你想要的,所以我猜你必须重命名第二个动作。

答案 2 :(得分: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请求,则最好重命名方法。

答案 3 :(得分: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);

        }

答案 4 :(得分: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);

}