【问题标题】:How to make MVC to select proper action in controller如何使 MVC 在控制器中选择正确的操作
【发布时间】:2010-03-31 12:45:50
【问题描述】:

谁能给我解释一件事。

我的控制器中有两种方法:

public ActionResult AddPredefinedTicket(int customerId) {...}

public ActionResult AddPredefinedTicket(int customerId, TicketTypes type, string additionalJsonParameters) {...} (here TicketTypes is enum)

我正在尝试使用类似 URL 的方式拨打电话

@987654321@

由于某种原因,我遇到了异常:

The current request for action 'AddPredefinedTicket' on controller type 'TicketController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult AddPredefinedTicket(Int32) on type CallCenter.CustomerService.Controllers.TicketController System.Web.Mvc.ActionResult AddPredefinedTicket(Int32, CallCenter.CustomerService.Data.Models.TicketTypes, System.String) on type CallCenter.CustomerService.Controllers.TicketController

但是,我不明白为什么 MVC 认为请求是模棱两可的。 正如您从我的 URL 调用中看到的那样,我既没有传递“type”也没有传递“additionalJsonParameters”参数。 我知道,additionalJsonParameters 是字符串,所以可以为空。

但是action也有“type”参数,即枚举,不能为null。

在我看来,MVC 应该使用 first action,但它没有。

你能解释一下为什么吗?

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

你是不是忘了用 [HttpGet]、[HttpPost] 属性来装饰你的方法。

【讨论】:

  • 好吧,我需要这两个操作作为获取操作
【解决方案2】:

您不能超载您的 ActionResults。

"控制器动作必须满足一些附加要求。用作控制器动作的方法不能重载。此外,控制器动作不能是静态方法。除此之外,您可以使用几乎可以作为控制器操作的任何方法。"

见:http://www.asp.net/Learn/mvc/tutorial-03-cs.aspx

【讨论】:

  • 谢谢伙计,现在我知道这是不可能的。但是,我仍然想知道,为什么这个案例没有在 MVC 中实现?你不知道为什么MVC有这样的限制吗?
【解决方案3】:

将第一种方法的逻辑放在第二种方法中。

在里面打个勾

if(type==null && string.IsNullOrEmpty(additionalJsonParameters){
//do logic from method 1
}
else{
//do logic from method 2
}

【讨论】:

  • 是的,这是一个选项。但我真的很讨厌控制器中的这种 if/then 逻辑。对我来说,使用不同的动作名称会更好
猜你喜欢
  • 2013-02-13
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多