Yulian
Yulian

Reputation: 6769

How to have a custom route without parameter names in ASP.NET MVC?

I have the following route to my method:

[HttpGet]
[Route("Company/Employees/{name}")]
public ActionResult Details(string name)

I want to access the employee with a name property of "John" by making a request to

Company/Employees/John

But now the route only works if I type:

Company/Employees?name=John

How can I fix this?

Edit:

This is my route config (inside an area)

context.MapRoute(
            "Company_default",
            "Company/{controller}/{action}/{id}",
            new { controller = "Employees", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "MySite.Areas.Company.Controllers" }
        );

Upvotes: 1

Views: 2903

Answers (2)

teo van kot
teo van kot

Reputation: 12491

As I already say, your default route have same sturture as your custom Contoller Route. Becouse {id} param is optional.

If you want to use your route you should define custom route in your RouteConfig BEFORE your default route and get rid of your Route Attribute on controller:

context.MapRoute(
            "DetailsCustom",
            "Company/Employees/{name}",
            new { controller = "Employees", action = "Details"},
            namespaces: new[] { "MySite.Areas.Company.Controllers" }
        );

Upvotes: 2

Kamal
Kamal

Reputation: 164

Add this before your other route:

context.MapRoute(
        "Company_default",
        "Company/{controller}/{id}",
        new { controller = "Employees", action = "Index", id =    UrlParameter.Optional },
        namespaces: new[] { "MySite.Areas.Company.Controllers" }
    );

as your previous one is picking up "John" as the "action" parameter

Upvotes: 0

Related Questions