[英]MVC5 ambiguous action methods in controller
我已经编写了一个C#MVC5 Internet应用程序,并对同一个控制器中的两个ActionResult方法有疑问。
我有两个Index ActionResult方法,如下所示:
public async Task<ActionResult> Index()
public async Task<ActionResult> Index(int? mapCompanyId)
我想浏览到Index()方法还是Index(int?mapCompanyId)方法,这取决于是否为mapCompanyId指定了值。
目前,我收到此错误:
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
我可以重写代码,以便只有一个Index ActionResult,但如果可能的话,宁愿有两个。
是否可以有两个具有相同名称的ActionResult,并且根据是否指定了值来执行相关的ActionResult。 如果是这样,是否易于实施?还是不值得花时间?
这是不可能的,因为您正在尝试为每种方法执行GET
请求。 ASP.NET MVC操作选择器不知道选择哪种方法。
如果可行,则可以使用HttpGet
或HttpPost
属性来区分每种HTTP请求类型的方法。 在您的情况下,听起来似乎没有道理。
您可以为操作重载分配不同的HTTP方法,如下所示:
[HttpGet]
public async Task<ActionResult> Index()
[HttpPost]
public async Task<ActionResult> Index(int? mapCompanyId)
然后,MVC运行时将能够基于请求HTTP方法选择适当的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.