The controller for path … was not found or does no

2019-02-19 07:47发布

问题:

I am writing an application using ASP.NET MVC 5 using c#. I have a need to add a global menu on the upper right hand side of the application. I was advised other SO to use action with ChildActionOnly attribute.

So here is what I have done.

I created a BaseController like this

public class BaseController : Controller
{

    [ChildActionOnly]
    public ActionResult ClientsMenu()
    {
        using (SomeContext db = new SomeContext())
        {
            return PartialView(db.Database.SqlQuery<Client>("SELECT * FROM clients").ToList());
        }
    }

}

Then I inherited all my controllers from BaseController like so

public class TasksController : BaseController
{

    public ActionResult Index(int ClientId)
    {
        ...
        return View();
    }

    public ActionResult Show(int SurveyId)
    {
        ...
        return View();
    }

}

To render the ClientsMenu in my layout I added the following code

@Html.Action("ClientsMenu", "Menus")

Now when I run my application I get the following error

The controller for path '/Tasks/Index' was not found or does not implement IController.

When I remove @Html.Action("ClientsMenu", "Menus") from the layout everything works fine but the global menu does not show of course.

What can I do to resolve this issue?

Updated Here is what I have done after the feedback I got from the comments below

public class TasksController : Controller
{
    [ChildActionOnly]
    public ActionResult ClientsMenu()
    {
        using (SomeContext db = new SomeContext())
        {
            return PartialView(db.Database.SqlQuery<Client>("SELECT * FROM clients").ToList());
        }
    }

    public ActionResult Index(int ClientId)
    {
        ...
        return View();
    }

    public ActionResult Show(int SurveyId)
    {
        ...
        return View();
    }

}

but still the same error

回答1:

Take ClientMenus Action out of the BaseController and put it into its own controller MenusController. You can then call that controller from your Views.

@Html.Action("ClientsMenu", "Menus")

In your example you don't have a MenusContoller which is what @Html.Action("ClientsMenu", "Menus") is looking for.

The Phil Haacked - Html.RenderAction and Html.Action article linked to by the other post provided a good example for you to follow.