Attribute based routing in MVC 5
we can define the route in the same
place where action method is defined
Here we specified the route for the controller GetElectronicItems
[Route("Products/Electronics/{id}")]
public
ActionResult GetElectronicItems(string id)
{
ViewBag.Id = id;
return
View();
}
To enable attribute based routing in
RouteConfig.cs we need to add the following in the RouteConfig file.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}
Optional
Parameter
We can also
specify if there is any optional parameter in the URL pattern defined by the
Route attribute with the “?” character.
[Route("Products/Electronics/{id?}")]
public ActionResult GetElectronicItems(int? id) {
ViewBag.Id = id; return View();
}
Route constraints
We can specify the constraints like if parameter
is int or string
[Route("Products/Electronics/{id:int}")]
Route Prefix
If we have multiple
action methods in a controller all using the same prefix we can use RoutePrefix
attribute on the controller instead of putting that prefix on every action
method.
Like
we can attach the following attribute on the controller
[RoutePrefix("Products")]
So
now our Route attribute on our action method does not need to specify the
common prefix
[Route("Electronics/{id}")]
Comments
Post a Comment