简体   繁体   中英

MVC5 ambiguous action methods in controller

I have coded a C# MVC5 Internet application and have a question about two ActionResult methods in the same controller.

I have two Index ActionResult methods as follows:

public async Task<ActionResult> Index()

public async Task<ActionResult> Index(int? mapCompanyId)

I am wanting to browse to either the Index() method or the Index(int? mapCompanyId) method, depending on if a value is specified for the mapCompanyId.

Currently, I am getting this error:

The current request for action 'Index' on controller type 'MapLocationController' is ambiguous between the following action methods:
System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] Index() on type CanFindLocation.Controllers.MapLocationController
System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] Index(System.Nullable`1[System.Int32]) on type CanFindLocation.Controllers.MapLocationController

I can rewrite my code so that there is only one Index ActionResult, but would rather have two if possible.

Is it possible to have two ActionResults with the same name, and depending on if a value is specified, the relevant ActionResult is executed. If so, is it easy to implement, or is it not worth the time?

This isn't possible since you're trying to do a GET request for each method. The ASP.NET MVC action selector doesn't know which method to pick.

If it makes sense and you're able you can use the HttpGet or HttpPost attributes to differentiate the method for each type of HTTP request. It doesn't sound like that makes sense in your case.

You can assign different HTTP methods to the action overloads like this:

[HttpGet]
public async Task<ActionResult> Index()

[HttpPost]
public async Task<ActionResult> Index(int? mapCompanyId)

MVC runtime will then be able to pick a proper action based on the request HTTP method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM