可能重复:
你可以重载在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());
}
当我打电话/测试/ 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
[编辑]
它不匹配订单甚至单个参数。
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'
}
你可以这样做,在一个控制器。 你将不得不改变第二种方法名。
[HttpPost]
public ActionResult ItemUpdates(List<ORDER> lns)
{
// Do Something
}
重载动作不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)
{
//...
}
public ActionResult ItemUpdates(object myInputValue)
{
if (myInputValue.GetType() == typeof(string)
// Do something
else if (myInputValue.GetType() == typeof(List<ORDER>))
// Do something else
}
然后,您可以把对象到你的类型的选择和正常操作。
在ASP.NET中这是不可能有重载方法没有ActionFilter属性来区分这些行动。 这样做的原因是,ActionInvoker(Controller基类中用于调用actiosn类)不能确定要调用哪个方法,因为它需要“问”一ModelBinder的(这是负责构建操作参数的对象),每过载,如果模型绑定器可以构建从通过HTTP请求参数对象。 对于简单的情况下,这会工作,但在更复杂的情况下,这将失败,因为该模型绑定器会在绑定多个重载的论据成功。 不允许在ASP.NET MVC重载是相当聪明的设计决策。
为了解决您的问题,您可以修复ItemUpdate
HTTP GET由刚刚离开第二个动作,距离其只有一个动作的动作,因为ModelBinder的不介意被作为例如URL参数传递的值是一个string
或int
。
[HttpGet]
public ActionResult ItemUpdate(string name)
{
return Content(name);
}
对于ItemUpdate
HTTP POST版本我建议你重新命名这些动作中的一个或只有一个动作,该列表的版本,因为更新单个ORDER
仅更新多个的具体情况ORDER
对象。
文章来源: ASP.net c#, Same name method that takes different argument type [duplicate]