EduLopez
EduLopez

Reputation: 719

How to use Action from the base controller without "action is ambiguous" on mvc .net?

Let's say I have an UserController with a Details(string id) action.

I want to create a new class called ClientController which inherits from UserController.

public class ClientController : UserController 
{ 

}

public class UserController 
{ 
    public ActionResult Details(string id)
    {
        var user = userService.GetById(id);
        return View(user);
    }
}

The problem comes when I want to do a request to Client/Details/xxxxx. The browser shows the error of

"Action is ambiguous between ... User....Details and Client....Details"

If I empty the Client Class and call directly on the browser Client/Details/xxxx the browser shows me the following error:

"The view 'Details' or its master was not found or no view engine supports the searched locations"

How can I make my web app use the Client/Details/xxxx request as User/Details/xxxx without creating code in the Clients class.

Upvotes: 3

Views: 2501

Answers (2)

Hemza Talha
Hemza Talha

Reputation: 97

Make the base class method , public virtual ...() Make the derived class method , public override ....() This will only execute the derived method when it hits the derived Controller.

If you don't implement the method in the derived Controller ,then the base method will be called.

If you don't make the base controller virtual , both of methods will be called and lead to routing ambiguous exception.

Upvotes: 1

dotnetstep
dotnetstep

Reputation: 17485

You have to follow basic OOPS related to C#

public class UserController : Controller
{
    // GET: User
    public virtual ActionResult Index()
    {
        return Json("User Controller", JsonRequestBehavior.AllowGet);
    }
}

public class ClientController : UserController
{
    // GET: User
    public override ActionResult Index()
    {
        return Json("Client Controller", JsonRequestBehavior.AllowGet);
    }
}

You have to make Base class method Virtual in order to override by Derived Class.

Now http://<<your host>>/User/Index Call UserController method.
Now http://<<your host>>/Client/Index Call ClientController method.

Update 1

If you want to use base class method then don't implement same method in derived class. Keep base class method public or public virtual.

public class UserController : Controller
    {
        public ActionResult Details(string id)
        {
            return Json("Test", JsonRequestBehavior.AllowGet);
        }
    }

    public class ClientController : UserController
    {

    }
  • In this case for both /Client/Details/1 or /User/Details/1 it will call method Inside UserController.
  • Make sure you have inherited UserController from Controller.
  • If you want to implement different version of method in derived class then you have to make that method virtual.

Upvotes: 5

Related Questions