ASP.NET MVC > URLs

Create URL based on Route defined in ASP.NET MVC

How to create a URL based on a Route defined?


To create a url based on Route defined in the App_Start/RouteConfig.cs page, we can use @Url.RouteUrl method.

Let’s assume that following route has been defined in the RouteConfig.cs file

APP_START/ROUTECONFIG.CS

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

To generate the url based on above Route, we can use @Url.RouteUrl method.

@Url.RouteUrl("MyCustomRoute")

Above code generates

/MyEmployees/outgoingurl

Because, we have not specified any parameters for controller and action method in the above RouteUrl method so the current page controller and action method is taken as default value.

@Url.RouteUrl("MyCustomRoute", new { action = "index", id = 12, Name = "Sheo" })

Above code generates

/MyEmployees/index/12?Name=Sheo

POINT OF INTEREST

Try different overload methods of the Url.RouteUrl method to get more customized and ready made url.

 Views: 14122 | Post Order: 76



Write for us






Hosting Recommendations