0

I was creating a sample mvc application and created two action methods (Index) in the Home controller.

public class HomeController : Controller
{
    //
    // GET: /Home/        
    public string Index()
    {
        return Index1();
    }

    public string Index(string message)
    {
        return "hello";
    }
}

And the index is set as the default action in running the application. On running the application I get the below error,

The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods: System.String Index(Int32) on type Mvc4example.Controllers.HomeController System.String Index(System.String) on type Mvc4example.Controllers.HomeController

What I expected is that with out query string it'll invoke the parameterless action method and if there is a query string message is passed then the action method with parameter will get invoked.

Can anyone explain why this behavior?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Venkatesh
  • 1,204
  • 1
  • 10
  • 18
  • It is the way MVC works, the parameters are not taken into account for selecting a method. If you want this sort of behaviour, you need to tweak it yourself, for example using an `ActionMethodSelectorAttribute` that looks at the query string and method parameters. – Daniel J.G. Oct 15 '14 at 09:56

3 Answers3

1

If you have two methods with same name, Http request attribute must be different

public class HomeController : Controller
{
    [HttpGet]        
    public string Index()
    {
        //...
    }

    [HttpPost]
    public string Index(string message)
    {
        //...
    }
}
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
0

That you have a third action like this

    public string Index(int id)
    {
            return "int";       
    }

would explain this behaviour

of course you don't need the parameterless action either, that's just a special case of the message one, where message is empty

dove
  • 20,469
  • 14
  • 82
  • 108
  • No I don't have that action method, but I still I get the same error even after adding that action method too which you mentioned. – Venkatesh Oct 15 '14 at 09:57
  • you don't need two actions here that are effectively the same, as others have answered already correctly as well, e.g. @Max Brodin – dove Oct 15 '14 at 10:00
0

Please check the answer in this post: Routing: The current request for action [...] is ambiguous between the following action methods for more details, but to summarize it:

You can only have a maximum of 2 action methods with the same name on a controller, and in order to do that one must be [HttpPost], and the other must be [HttpGet].

Since both of your methods are GET, you should either rename one of the action methods or move it to a different controller

Community
  • 1
  • 1
SmartDev
  • 2,802
  • 1
  • 17
  • 22