Venugopal M
Venugopal M

Reputation: 2412

How to pass a parameter in place of controller name in ASP MVC?

I would like to know about this. As we already know, the first parameter to a URL in ASP MVC would be a controller name as in

http://www.somedomain.com/Home/Index

Here, Home is controller and Index is action. So if some one wanted to pass a value to this URL, he would do so like

http://www.somedomain.com/Home/Index/abc-power-corporation

where abc-power-corporation is a string identifier for a registered organization. This is pretty much simple and routine. But I would like to know if there is a way to use this URL.

http://www.somedomain.com/abc-power-corporation

so that the URL is much friendlier and easier. This should take me to the profile of the desired company.

Upvotes: 1

Views: 170

Answers (1)

JLRishe
JLRishe

Reputation: 101652

Yes, you can do this in RouteConfig.cs.

Replace this:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

With this:

routes.MapRoute(
    name: "RetrieveById",
    url: "{id}",
    defaults: new { controller = "ControllerNametoUse", 
                    action = "ActionNameToUse", id = UrlParameter.Optional }
);

Note that it wouldn't be all that advisable to use both of these at the same time because it would create ambiguity, but it's still possible to use both of them as long as Action is explicitly specified in the URL and you specify the RetrieveById first in RouteConfig.cs.

You could also add more specific routes to get around the ambiguity issue:

routes.MapRoute(
    name: "Customers",
    url: "Customers/{action}/{id}",
    defaults: new { controller = "Customers", action = "Index", id = UrlParameter.Optional }
);

These would need to be specified before the RetrieveById route so that they take precedence.

Upvotes: 3

Related Questions