c# mvc 3, action overloading?

2019-01-23 17:47发布

问题:

I have been trying to overload my index method.

Here are my index methods:

[ActionName("Index")]
public ActionResult IndexDefault()
{
}

[ActionName("Index")]
public ActionResult IndexWithEvent(string eventName)
{
}

[ActionName("Index")]
public ActionResult IndexWithEventAndLanguage(string eventName, string language)
{
}

This keeps casting:

The current request for action 'Index' on controller type 'CoreController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult IndexDefault() on type ManageMvc.Controllers.CoreController System.Web.Mvc.ActionResult IndexWithEvent(System.String) on type ManageMvc.Controllers.CoreController System.Web.Mvc.ActionResult IndexWithEventAndLanguage(System.String, System.String) on type ManageMvc.Controllers.CoreController

Is it not possible to overload the index action with 3 different GET methods?

Also, if it is possible, what would be the correct route? I have this:

routes.MapRoute(
                "IndexRoute", // Route name
                "{eventName}/{language}/Core/{action}", // URL with parameters
                new { controller = "Core", action = "Index", eventName = UrlParameter.Optional, language = UrlParameter.Optional }
);

The url would look like:

localhost/Core/Index

localhost/event_name/Core/Index

localhost/event_name/language/Core/Index

回答1:

Overloading like that isn't going to work.

Your best option is to use default values and then making the route values optional (like you already have them):

public ActionResult Index(string eventName = null, string language = null)
{
}

I'm not sure you're going to get the route to look the way you want with a single route definition though. You're probably going to have to define three different routes and map each back to your single Action method.