ASP.NET MVC > Controller

Rename a controller in ASP.NET MVC

How to rename a controller in ASP.NET MVC?


A controller can’t be renamed like an action method, however the route can be changed so that you do not need to stick with the url that is directly related with the controller name.

To do this, go to App_Start/RouteConfig.cs and write following code.

ROUTECONFIG CODE
using System.Web.Mvc;
using System.Web.Routing;
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
        name: "MyCustomRoute",
        url: "MyEmployees/{action}/{id}",
        defaults: new
        {
            controller = "PersonalDetail",
            action = "Create",
            id = UrlParameter.Optional
        }
        );
        routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional
        }
        );
    }
}

Notice the code highlighted above. Even if the controller name is PersonalDetail, the url should look like http://localhost:63087/MyEmployees in order to go to Create view of PersonalDetailController. Similarly, to
browser any other action method of the PersonalDetailController, we need to browse by prefixing with MyEmployees as if the controller name is MyEmployeesController.

Eg.

  • http://localhost:63087/MyEmployees/Index - for Index action method of the PersonalDetailController
  • http://localhost:63087/MyEmployees/Edit/1 - for Edit action method of the PersonalDetailController
  • http://localhost:63087/MyEmployees/Delete/1 - for Delete action method of the PersonalDetailController
 Views: 28560 | Post Order: 49



Write for us






Hosting Recommendations