重写虚拟方法,但使用新签名:因此可以使用自定义模型绑定器
我有一个定义了虚拟函数的抽象类:
public abstract class ContentController
{
public virtual ActionResult Index();
}
我有一个从上述基类派生的类:
public class CartController : ContentController
我需要 CartController 能够在其 Index 方法上使用自定义模型绑定器绑定购物车。通常看起来像这样的东西:
public ActionResult Index(Cart cart)
如果我只是将 Index(Cart) 函数放入 CartController 类中,我会收到此错误:
The current request for action 'Index' on controller type 'CartController' is ambiguous between the following action methods:
ActionResult Index() on type CartController
ActionResult Index(Cart) on type CartController
到目前为止我想出的唯一解决方案是重命名我的模型绑定函数并从重写 Index 方法:
public override ActionResult Index()
{
return RedirectToAction("IndexWithCart");
}
public ActionResult IndexWithCart(Cart cart)
{
return View("Index", cart);
}
可行,但我的 URL 是 /Cart/IndexWithCart。有没有什么方法可以实现这一点,并且仍然只有 /Cart URL,而不修改基类?
I've got an abstract class with a virtual function defined:
public abstract class ContentController
{
public virtual ActionResult Index();
}
I've got a class that derives from the above base class:
public class CartController : ContentController
I need the CartController to be able to bind a cart with a custom model binder on its Index method. Something that would normally look like this:
public ActionResult Index(Cart cart)
If I just place the Index(Cart) function into the CartController class, I get this error:
The current request for action 'Index' on controller type 'CartController' is ambiguous between the following action methods:
ActionResult Index() on type CartController
ActionResult Index(Cart) on type CartController
The only solution I've come up with thus far is to rename my model binding function and redirect from the overriden Index method:
public override ActionResult Index()
{
return RedirectToAction("IndexWithCart");
}
public ActionResult IndexWithCart(Cart cart)
{
return View("Index", cart);
}
That works, but then my URL is /Cart/IndexWithCart. Is there any way to accomplish this and still have just the /Cart URL, without modifying the base class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,当您有 /Cart URL 时,只需将您的路由设置为指向 IndexWithCart 操作即可:
Yeah just setup your route to point to the IndexWithCart action when you have the /Cart URL:
怎么样(对于基本控制器):
其次是(对于继承的控制器):
可能有效。
[编辑] - 第二种方法可能是尝试(基类):
对于控制器:
我现在已经彻底崩溃了:)
how about (for the base controller):
followed by (for the inherited controller):
might work.
[edit] - a second way may be to try (base class):
and for the controller:
i'm all thunked out now :)
那么使用[HttpPost]怎么样
操作“索引”在您的基本控制器和子控制器中不会有歧义
[HttpPost]
公共 ActionResult 索引(购物车)
how about using [HttpPost] then
action 'Index' will not be ambiguous in your Base Controllor and child Controllor
[HttpPost]
public ActionResult Index(Cart cart)