Create a URL based on a Route Data defined Example

Updated on     Kisan Patel

To create a url based on route data defined, we can use @Url.RouteUrl method.

Let’s assume that following route has been defined

routes.MapRoute(
     name: "MyRoute",
     url: "MyStudents/{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("MyRoute")

the above code will generate following url

/MyStudents/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 = 54, Name = "Kisan" })

the above code will generate following url

/MyStudents/Index/54?Name=Kisan


ASP.NET MVC

Leave a Reply