Attribute based routing in MVC 5 ?
Attribute Based Routing:Attribute based routing can defined as route configuration in the same place where action method is defined. This is way of setting the route configuration for every single action method in same section where action is defined for better usage and fast configuration.
To enable Attribute based routing we need to add a small section into the RouteConfig.cs file,
To enable Attribute based routing we need to add a small section into the RouteConfig.cs file,
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}
Optional Parameter: We can specify the optional parameters in the URL in route attribute only using "?" character.
[Route("Products/Electronics/{id?}")]
public ActionResult GetElectronicItems(int? id) {
ViewBag.Id = id; return View();
}
Route Constraints: Specify parameter constraints placing the constraint name after the parameter name separated by colon.Here the action methods needs a id of int type to be worked upon.
[Route("Products/Electronics/{id:int}")]
Route Prefix: If there are a lot of action in a controller , then we can choose different prefix for them using Route Prefix attribute.
[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