Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - c# mvc 3, action overloading?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...