重用一个函数来处理2种不同的数据类型作为第二个参数

时间:2013-08-21 16:52:29

标签: c# asp.net-mvc-3

我必须更改我的控制器来处理2个不同的查询字符串,但是使用相同数量的参数,所以看起来我不能拥有2个具有相同名称和args数量的函数:

错误

The current request for action 'FollowUp' on controller type 'ContactController' is ambiguous between the following action methods:

所以我该怎么做?

* 字符串#1字符串,int * ?接触=真和ID = 7889876

字符串#2字符串,字符串 ?接触=真安培; PID = AWRE-9876-POKJ-112WQ

当前控制器

 [HttpGet]
 public ActionResult FollowUp(string contacted, int id) {}

谢谢!

2 个答案:

答案 0 :(得分:2)

不是创建两个函数,而是使用三个参数创建单个函数,并相应地使用逻辑。

示例:

[HttpGet]
public ActionResult FollowUp(string contacted, string pid, int? id) 
{
   if(!string.IsNullOrEmpty(contacted) && !string.IsNullOrEmpty(pid)) {
      // do your logic.
   }
   else if(!string.IsNullOrEmpty(contacted) && id != null) {
      // do your logic.
   }
}

注意:id设为nullable不需要任何值格式网址。如果你没有向这个论点传递任何东西,它将为null。

希望这会有所帮助。

答案 1 :(得分:1)

您不能拥有多个可以响应GET请求的同名操作。您还可以将其他参数添加到您的操作中,并通过检查存在哪些参数来决定您要执行的操作。

[HttpGet]
public ActionResult FollowUp(string contacted, int? id, string pid) {}