Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to override a MVC Controller Action?

I am adapting an open source project (NopCommerce). It is a great software and supports extensibility using plugins. For one plugin, I would like to add information to a view, to do that, I want to inherit from the Controller and override the actions I need to change. So this is my controller:

public class MyController : OldController{
//stuff

public new ActionResult Product(int productId)
{
 //Somestuff
}

}

I changed the route from my plugin, but when this action get called I get the following error:

The current request for action 'Product' on controller type 'MyController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Product(Int32) on type MyPlugin System.Web.Mvc.ActionResult Product(Int32) on type OldController

Is there any way I can override this method? (ps: I can't use the override keyword because it is not marked as virtual, abstract or override in the OldController)

thanks, Oscar

like image 534
JSBach Avatar asked Feb 20 '13 02:02

JSBach


People also ask

Can we override action method in MVC?

If we have to overload the action Method in asp.net MVC then we can not do it directly. We have to change the ActionName like this code snippet. Now to run the controller GetEmpName action method with just give the URL like this: http://localhost:49389/Home/GetEmpName.

Can you overload action methods?

A method used as a controller action cannot be overloaded..

Can a controller have multiple actions with same name?

This will fail when you will call these because the MVC framework won't know which one to call. You have two solutions to make MVC routing know which action to use. First, you can change the name.

How many action methods are there in MVC?

Action Result It is a base class for all type of action results. The diagram shown below describes about abstract class of Action Result. There are two methods in Action Result. One is ActionResult() and another one is ExecuteResult().


1 Answers

If OldController's method is few, Redeclare like this.

public class MyController : Controller 
{
    private OldController old = new OldController();

    // OldController method we want to "override"
    public ActionResult Product(int productid)
    {
        ...
        return View(...);
    }

    // Other OldController method for which we want the "inherited" behavior
    public ActionResult Method1(...)
    {
        return old.Method1(...);
    }
}
like image 117
ebattulga Avatar answered Nov 10 '22 03:11

ebattulga