How to override an action method in a controller? Can anyone explain with a small example. And one more thing to ask , can we do this without virtual keyword?
如何覆盖控制器中的操作方法?任何人都可以用一个小例子来解释。还有一件事要问,我们可以在没有虚拟关键字的情况下这样做吗?
1 个解决方案
#1
1
As far as i m understanding your question these are the answers :
至于我理解你的问题,这些是答案:
First Answer :
第一个答案:
it's not possible to have two controller actions with the same name but with a different result also:
不可能有两个具有相同名称但具有不同结果的控制器操作:
For example:
ActionResult YourAction() { ... }
FileContentResult YourAction() { ... }
In MVC you can also do this :
在MVC中你也可以这样做:
[HttpGet]
[ActionName("AnyAction")]
ActionResult YourAction(firstModel model1) { ... }
[HttpPost]
[ActionName("AnyAction")]
FileContentResult YourAction(secondModel model1) { ... }
The main idea here is that you can use the ActionNameAttribute to name several action methods with the same name.
这里的主要思想是您可以使用ActionNameAttribute来命名具有相同名称的多个操作方法。
----------------------------------------------------------------OR--------------------------------------------------------------
Second Answer :
第二个答案:
[NonAction]
public override ActionResult YourAction(FormCollection form)
{
// do nothing or throw exception
}
[HttpPost]
public ActionResult YourAction(FormCollection form)
{
// your implementation
}
#1
1
As far as i m understanding your question these are the answers :
至于我理解你的问题,这些是答案:
First Answer :
第一个答案:
it's not possible to have two controller actions with the same name but with a different result also:
不可能有两个具有相同名称但具有不同结果的控制器操作:
For example:
ActionResult YourAction() { ... }
FileContentResult YourAction() { ... }
In MVC you can also do this :
在MVC中你也可以这样做:
[HttpGet]
[ActionName("AnyAction")]
ActionResult YourAction(firstModel model1) { ... }
[HttpPost]
[ActionName("AnyAction")]
FileContentResult YourAction(secondModel model1) { ... }
The main idea here is that you can use the ActionNameAttribute to name several action methods with the same name.
这里的主要思想是您可以使用ActionNameAttribute来命名具有相同名称的多个操作方法。
----------------------------------------------------------------OR--------------------------------------------------------------
Second Answer :
第二个答案:
[NonAction]
public override ActionResult YourAction(FormCollection form)
{
// do nothing or throw exception
}
[HttpPost]
public ActionResult YourAction(FormCollection form)
{
// your implementation
}