1

I would like MVC to be able to handle the following two urls

http://www.com/Author/Edit/1

http://www.com/Editor/Edit/2

in my AuthorController I have a method:

AuthorController.cs
public void Edit(int AuthorId) {
}

 EditorController.cs
 public void Edit(int EditorId) {
 }

Is this possible, if so, how do I setup the route config to handle this?

This default route has "id" I want a more descriptive var name for each of the action.

I am able to get it to work. But wasn't sure if it is the best practice or the right method.

What I did is created two new entries in the route config to handle the different variations.

1

1 Answer 1

1

Define route for each Edit action in RouteConfig.cs file:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "AuthorEdit",
            url: "author/edit/{AuthorId}",
            defaults: new { controller = "AuthorController", action = "Edit"                    },
            constraints: new { AuthorId= "\\d+" }
        );

        routes.MapRoute(
        name: "EditorEdit",
        url: "editor/edit/{EditorId}",
        defaults: new { controller = "EditorController", action = "Edit" },
        constraints: new { EditorId= "\\d+" }
    );

or if you want use Attribute Routing, modify RouteConfig.cs file:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // Enable attribute routing
        routes.MapMvcAttributeRoutes();

and in controllers:

AuthorController.cs
[Route("author/edit/{AuthorId}")]
public void Edit(int AuthorId) {
}

 EditorController.cs
[Route("editor/edit/{EditorId}")]
 public void Edit(int EditorId) {
 }
Sign up to request clarification or add additional context in comments.

1 Comment

That is what I did to begin with was define custom routes. I just wanted to make sure I was going the correct direction. I do like the attribute method better. Will have to try it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.