[英]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. 我已经编写了一个C#MVC5 Internet应用程序,并对同一个控制器中的两个ActionResult方法有疑问。
I have two Index ActionResult methods as follows: 我有两个Index ActionResult方法,如下所示:
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. 我想浏览到Index()方法还是Index(int?mapCompanyId)方法,这取决于是否为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. 我可以重写代码,以便只有一个Index ActionResult,但如果可能的话,宁愿有两个。
Is it possible to have two ActionResults with the same name, and depending on if a value is specified, the relevant ActionResult is executed. 是否可以有两个具有相同名称的ActionResult,并且根据是否指定了值来执行相关的ActionResult。 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. 这是不可能的,因为您正在尝试为每种方法执行
GET
请求。 The ASP.NET MVC action selector doesn't know which method to pick. ASP.NET MVC操作选择器不知道选择哪种方法。
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. 如果可行,则可以使用
HttpGet
或HttpPost
属性来区分每种HTTP请求类型的方法。 It doesn't sound like that makes sense in your case. 在您的情况下,听起来似乎没有道理。
You can assign different HTTP methods to the action overloads like this: 您可以为操作重载分配不同的HTTP方法,如下所示:
[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. 然后,MVC运行时将能够基于请求HTTP方法选择适当的操作。
You can use a custom Action Method Selector http://www.codeproject.com/Articles/291433/Custom-Action-Method-Selector-in-MVC 您可以使用自定义操作方法选择器http://www.codeproject.com/Articles/291433/Custom-Action-Method-Selector-in-MVC
https://agileshoptalk.wordpress.com/2012/02/03/custom-action-method-overloading-in-mvc3/ https://agileshoptalk.wordpress.com/2012/02/03/custom-action-method-overloading-in-mvc3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.