user1873572
user1873572

Reputation: 21

Multiple Controllers in ASP.NET MVC

I have one site and the controller is a name of the user like /John/NewPage, same thing for Mary.

How can I do this without having to create a controller for each new user?

Thks

Upvotes: 2

Views: 831

Answers (2)

JoshNaro
JoshNaro

Reputation: 2097

You could do something like this. Define a controller named something like "UserController" then use custom routes so that it isn't necessary to have "UserController" in the URL:

context.MapRoute(
    "User_Route", // Route name
    "{userName}/{action}", // URL with parameters
    new { 
      controller = "UserController",
      action = "NewPage"
    } // Parameter defaults
);

With that setup, the "/Mary/NewPage" URL would call UserController.NewPage("Mary"), "/John/EditPage" would call UserController.EditPage("John"), and just "/Jane" would call UserController.NewPage("Jane").

You would also need to define routes for different controllers above that route so they would get called first. For example:

context.MapRoute(
    "SomeOther_Route", // Route name
    "SomeOtherController/{action}/{id}", // URL with parameters
    new { 
      controller = "SomeOtherController"
    } // Parameter defaults
);

The above URLs will still work, but now this URL "/SomeOtherController/DefinedAction/12" will call something like SomeOtherController.DefinedAction(12).

Upvotes: 0

Igor
Igor

Reputation: 15893

Look into custom routing. Something like:

    context.MapRoute(
        "User_default", // Route name
        "{userName}/{controller}/{action}/{id}", // URL with parameters
        new { id = UrlParameter.Optional } // Parameter defaults
    )

But you will have to take care of forming these url's yourself.

Upvotes: 1

Related Questions