Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify the namespace for which controller to call in HtmlHelper.Action(string, string, object)?

I have two controllers with identical names, one of which lives in the "Admin" area and one in the default area (which I believe resolves as an empty string for area).

The following call:

HtmlHelper.Action("Action", "DuplicateController", new { parameterValue = "test" } );

Doesn't appear to be able to resolve the difference between my ProjectA.Controllers.DuplicateController and ProjectB.Controllers.DuplicateController, even if I specify the area as "" by adding it as follows:

HtmlHelper.Action("Action", "DuplicateController", new { parameterValue = "test", area = "" } );

I know I should be able to resolve this by specifying a route when I register them on application startup, but is it possible to specify a fully-qualified namespace directly to the controller I know I need to call right in the action method?

e.g. something like the following would solve my problem:

HtmlHelper.Action("Action", "ProjectB.Controllers.DuplicateController", new { parameterValue = "test" } );
like image 687
Ryan Weir Avatar asked Nov 25 '13 00:11

Ryan Weir


1 Answers

Like you suggested, I believe you'll have to add namespaces to the routes for both of your ambiguous controllers in your RouteConfig.cs file and your AdminAreaRegistration.cs file. For an example, see this StackOverflow post.

So, you can either add the "namespaces" argument to the default route as in the above post or create a route for each "Duplicate" controller.

In your RouteConfig.cs:

routes.MapRoute(
    name: "Duplicate",
    url: "Duplicate/{action}/{id}",
    defaults: new { controller = "Duplicate", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] { "MyMvcApplication.Controllers" }
);

And in your AdminAreaRegistration.cs:

context.MapRoute(
    "Admin_Duplicate",
    "Admin/Duplicate/{action}/{id}",
    new { controller = "Duplicate", action = "Index", id = UrlParameter.Optional },
    new[] { "MyMvcApplication.Areas.Admin.Controllers" }
);
like image 94
William Avatar answered Oct 07 '22 22:10

William