Reputation: 3095
I have an ASP.NET Core 3 MVC web app and I have a couple of controllers.
I am trying to form my links to access these controllers and I am unsure what I am doing wrong.
Controller names: Exhibitors
, DemoQueue
Each controller has an Index
action which takes 2 int
type parameters
public IActionResult Index(int eventId, int companyId)
And here is my relevant Startup.cs
code
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
So it is my understanding that I can browse to these 2 actions by these urls:
Exhibitors/1/2
DemoQueue/3/4
But it seems I have to use this longwinded value:
Exhibitors/Index?eventId=1&companyId=2
Is there a way to set a route to enable me to go to [controller]/id/id
? But go to a different controller e.g. Exhibitors
or DemoQueue
Upvotes: 0
Views: 2108
Reputation: 43860
You can change your code to these
public class ExhibitorsController:Controller
[Route("~/Exhibitors/{eventId}/{companyId}")]
public IActionResult Index (int eventId, int companyId)
and
public class DemoQueueController:Controller
[Route("~/DemoQueue/{eventId}/{companyId}")]
public IActionResult Index (int eventId, int companyId)
Upvotes: 1
Reputation: 21476
You didn't have your custom route template defined. In your startup.cs
, all you had was the default routing template.
To map requests like Exhibitors/1/2
and DemoQueue/3/4
to their corresponding controllers Index
method, you need to add the following before the default conventional routing template:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "exhibitors-custom",
pattern: "exhibitors/{eventId:int}/{companyId:int}",
defaults: new { controller = "exhibitors", action = "index" }
);
endpoints.MapControllerRoute(
name: "demoqueue-custom",
pattern: "demoqueue/{eventId:int}/{companyId:int}",
defaults: new { controller = "demoqueue", action = "index" }
);
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
You can mix the use of conventional routing and attribute routing, but it's typical to use conventional routes for controllers returning HTML for browsers, and attribute routing for controllers serving RESTful APIs.
Upvotes: 3