Home > Software engineering >  How to Dynamically Route in ASP.net 6.0 MVC
How to Dynamically Route in ASP.net 6.0 MVC

Time:07-31

I have a problem where I want to route to a page like so:

site.com/Company/StackOverflow site.com/Company/Microsoft

I want to take the name of the company from the Route and pass it as parameter into my IActionResult Index() function so that I can retrieve it from a database. How could I do this so I don't have to explicitly call out the Route

This is what I currently have, but what comes into my controller is CompanyName = null

In my Program.cs

app.MapControllerRoute(
    name: "company",
    pattern: "{controller=Company}/{action=Index}/{CompanyName}");

In my CompanyController:

public IActionResult Index(string CompanyName)
{
    string test = CompanyName;
    //Fetch info for CompanyName and build model
    //Return view with model
    return View();
}

If Possible, I'd like to avoid a URL that has the following site.com/Company?CompanyName=Microsoft.com

CodePudding user response:

I think you are missing the defaults parameter in the MapControllerRoute method.

app.MapControllerRoute(
    name: "company",
    pattern: "{controller=Company}/{action=Index}/{CompanyName}",
    defaults: new { controller = "Company", action = "Index" });
  • Related