ASP.net c#,采用不同参数类型的同名方法

时间:2012-07-18 18:45:56

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

  

可能重复:
  Can you overload controller methods in ASP.Net MVC?

我需要2个采用不同类型参数的方法。所以我试过了,

[HttpPost]
public ActionResult ItemUpdate(ORDER ln)
{
   // do something
}

[HttpPost]
public ActionResult ItemUpdate(List<ORDER> lns)
{
  // Do Something
}

但它不起作用。

编译时没有错误,但运行时会出错。

我如何编写代码以使其有效?

谢谢!

[编辑]

[HttpGet]
public ActionResult ItemUpdate(string name)
{
    return Content(name);
}

[HttpGet]
public ActionResult ItemUpdate(int num)
{
    return Content(num.ToString());
}

当我调用/ Test / ItemUpdate /

它出错了,

Server Error in '/' Application.
The current request for action 'ItemUpdate' on controller type 'OrderController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult ItemUpdate(System.String) on type Ecom.WebUI.Controllers.OrderController
System.Web.Mvc.ActionResult ItemUpdate(Int32) on type Ecom.WebUI.Controllers.OrderController 

[编辑]

即使是单个参数也与ORDER不匹配。

if (lns.GetType() == typeof(ORDER))
{
  // always false
}else{
  // also I can not cast the object.
  ORDER ln = (ORDER)lns; //Unable to cast object of type 'System.Object' to type 'ORDER'
}

4 个答案:

答案 0 :(得分:2)

MVC不支持重载操作。调度员无法区分这两个操作之间的区别。您可以通过将[HttpGet]属性设置为[HttpPost]属性,将另一个属性设置为[HttpPost] public ActionResult ItemUpdate(object arg) { if (arg.GetType() == typeof(ORDER)) { return ItemUpdateOrder((Order)arg); } else if (arg.GetType() == typeof(List<ORDER>)) { return ItemUpdateList((List<Order>)arg); } } public ActionResult ItemUpdateOrder(ORDER ln) { //... } public ActionResult ItemUpdateList(List<ORDER> lns) { //... } 属性来解决此问题。

如果这不是一个选项(或者如果你有三个或更多的重载),你总是可以自己调度Action,使用一个object参数并使用运行时类型标识来选择要调用的正确函数。 E.g:

{{1}}

答案 1 :(得分:1)

你不能在控制器中这样做。您将不得不更改第二个方法名称。

[HttpPost]
public ActionResult ItemUpdates(List<ORDER> lns)
{
  // Do Something
}

答案 2 :(得分:0)

public ActionResult ItemUpdates(object myInputValue)
{
    if (myInputValue.GetType() == typeof(string)
    // Do something
    else if (myInputValue.GetType() == typeof(List<ORDER>))
    // Do something else
}

然后,您可以将对象强制转换为您选择的类型并正常操作。

答案 3 :(得分:0)

在ASP.NET中,不能使用没有ActionFilter属性的重载方法来区分这些操作。这样做的原因是ActionInvoker(一个在Controller基类内部用来调用actiosn的类)无法确定调用哪个方法,因为它需要为每个方法“询问”一个ModelBinder(它们负责构造动作参数对象)如果ModelBinder可以从传递的HTTP请求构造该参数对象,则重载。对于简单的场景,这可以工作,但在更复杂的场景中,这将失败,因为ModelBinder将成功绑定多个重载的参数。不允许ASP.NET MVC中的重载是一个非常聪明的设计决策。

要解决您的问题,您可以修复ItemUpdate HTTP GET操作,只需将第二个操作留下并只执行一个操作,因为ModelBinder不介意作为URL参数传递的值是否为stringint

[HttpGet]
public ActionResult ItemUpdate(string name)
{
    return Content(name);
}

对于ItemUpdate HTTP POST版本,我建议重命名其中一个操作或只有一个操作,列表版本因为更新单个ORDER只是更新多个的特定情况ORDER个对象。

相关问题