Dot Net Stuff

Attributes in Routing in ASP.NET MVC with example:


Routing in Asp.NET MVC is how ASP.NET MVC matches a URI to an action. ASP.NET routing enables you to use URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users. You can find more details about ASP.NET MVC Routing in separate articles. Here, I am going to discuss about Attributes in Routing in ASP.NET MVC.Now, you are able to know what following code says.

 
public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Category/{action}/{categoryName}",
        "~/categories.aspx",
        true,
        new RouteValueDictionary 
            {{"categoryName", "MVC"}, {"action", "show"}});
}
void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

Here, we have defined a route for the application. When the route definitions are co-located with the actions, within the same source file rather than being declared on an external configuration class, it can make it easier to reason about the mapping between URIs and actions. The previous route definition would be set using the following, simple attribute:

 
[Route("{categoryId:int}/{categoryTitle}")]
public ActionResult Show(int categoryId) { ... }

How to Enable Attribute Routing

It is very easy to enable Attribute in Routing,You just need to call MapMvcAttributeRoutes during configuration. Following is an example to enable attribute in Routing.

 
public static void RegisterRoutes(RouteCollection routes)
{
 routes.MapMvcAttributeRoutes();    
routes.MapPageRoute("",
        "Category/{action}/{categoryName}",
        "~/categories.aspx",
        true,
        new RouteValueDictionary 
            {{"categoryName", "MVC"}, {"action", "show"}});
}

Attribute Routing in ASP.NET MVC Example

After Enabling the attributes in application you can define a route attribute on top of an action method. The following is the example of a Route Attribute in which routing is defined where the action method is defined. In the following example, I am defining the “Route” attribute on top of the action method.

 
public class HomeController : Controller
{
    //URL: /Category
    [Route("Category")]
    public ActionResult Index(){
        ViewBag.Message = "Welcome to ASP.NET MVC Routing!";
        return View();
    }
}

Attribute Routing with Optional Parameter

It is possible that we may have the requirement for something that must accept some options parameter. We can define an optional parameter in the URL pattern by defining a question mark (“?") to the route parameter. We can also define the default value by using parameter=value.

 
public class HomeController : Controller
{
  // Optional URI Parameter
  // URL: /Category/
  // URL: /Category/MVC
    [Route("Category /{ categoryName ?}")]
    public ActionResult Show(string categoryName){
        ViewBag.Message = "This is Attribute Routing with Optional Parameter ASP.NET MVC!";
        return View();
    }
   // Optional URI Parameter with default value
// URL: /Category/
  // URL: /Category/MVC
    [Route("Category /{ categoryName ="MVC"}")]
    public ActionResult Show(string categoryName){
        ViewBag.Message = "This is Attribute Routing with Default ValueASP.NET MVC!";
        return View();
    }
}

Route Prefixes in Routing in ASP.NET MVC

Sometimes, we may got the requirements which include some prefix in the entire Action Methods. We can also set a common prefix for the entire controller (all action methods within the controller) using the “RoutePrefix” attribute. Following is an example shows how we can define Route Prefix.

 
[RoutePrefix("Category")]
public class HomeController : Controller
{
    // URL: /Category/
    [Route]
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to Dot Net Stuff!";
        return View();
    }
  // Optional URI Parameter
  // URL: /Category/
  // URL: /Category/MVC
    [Route("{ categoryName }")]
    public ActionResult Show(string categoryName)
    {
        ViewBag.Message = "Welcome to ASP.NET MVC Category!";
        return View();
    }
}

If we want to override the route prefix, we should use a tide (~) sign with the Route attribute. Following is an example which shows how it can be done.

 
[RoutePrefix("Category")]
public class HomeController : Controller
{
    // URL: /OverideRoutePrefix/
    [Route("~/NewCategory")]
    public ActionResult Index()
    {
        ViewBag.Message = "Override the route prefix!";
        return View();
    }
}

Defining Default Route using Route Attribute in ASP.NET MVC Routing

If we want to define default route for any controller, We can do it by defining a Route attribute on top of the controller, to capture the default action method as the parameter. Following example shows how it can be done.

 
[RoutePrefix("Category")]
[Route("action=index")]
public class HomeController : Controller
{
    // URL: /Category/
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC Routing!";
        return View();
    } 
    // URL: /Category/NewCategory
    public ActionResult NewIndex()
    {
        ViewBag.Message = "This is new Category for ASP.NET MVC!";
        return View();
    }
}

Defining Route name in ASP.NET MVC

To define route name in ASP.NET MVC Routing. We can also define a name of the route to allow easy URI generation. Following example show how to do that.

 
[Route("Category",  Name = "CategoryURL")]
public ActionResult Index()
{
        ViewBag.Message = "Welcome to ASP.NET MVC Routing!";
        return View();
}

And to generate URI from above definition of Routing. We can generate URI using Url.RouteUrl method.

 
Category URI

Defining Area in ASP.NET MVC Routing

Areas are logical grouping of Controller, Models and Views and other related folders for a module in MVC applications. By convention, a top Areas folder can contain multiple areas. Using areas, we can write more maintainable code for an application cleanly separated according to the modules.

If we have Areas in our application, than we can define the "Area" name from the controller that belongs to the using RouteArea attribute. If we define the “RouteArea” attribute on top of the controller, we can remove the AreaRegistration class from global.asax. Following is an example to shows how to defining Area in Asp.NET MVC Routing.

 
[RouteArea("PostArea")]
[RoutePrefix("Category")]
[Route("action=index")]
public class HomeController : Controller
{
    // URL: /PostArea/Category/
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC Routing!";
        return View();
    }
}

Summary:We can define Routing in a separate file but using Attribute Routing allows us more control over the URIs in our MVC web application. The earlier way of routing (convention-based routing) is fully supported by this version of MVC. We can also use both type of routing in the same project. To know convention-based routing you can find it in a separate article.


Keen to hear from you...!

If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to here from you. Please MakeUseOf Contact and i will be more than happy to help.

About the author

Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional and loves to work with Microsoft .Net. He's usually writes articles about .Net related technologies and here to shares his experiences, personal notes, Tutorials, Examples, Problems & Solutions, Code Snippets, Reference Manual and Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity Framework, WCF, SQL Server, jQuery, Visual Studio and much more...!!!

Loading