Blog

Filter posts by Category Or Tag of the Blog section!

Attribute routing with asp.net MVC5

Friday, 14 February 2014

Until the latest version of asp.net (asp.net mvc4), routing was handling by Convention-based routing to matches a URI to an Action in a separate class (RouteConfig ) registered in global.asax. but in asp.net MVC5  you can use attribute routing. It means you can use the attribute to set routes to your actions. It's too easy getting started with attribute routing, you just need to refer RouteConfing.cs in App_Start folder and add routes.MapMvcAttributeRoutes(); in RegisterRoutes:

 

 public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

 

Now you should define an attribute for your actions, create a simple Data class and some fake data:

 

   public class SampleController : Controller
    {
       private List<Data> _datas = new List<Data>()
        {
            new Data {Id = 1, Name = "Ehsan"},
            new Data {Id = 2, Name = "Micheal"},
            new Data {Id = 3, Name = "Elizabeth"},
            new Data {Id = 4, Name = "Sia"},
            new Data {Id = 5, Name = "Behzad"},
            new Data {Id = 6, Name = "Emrah"},
            new Data {Id = 7, Name = "Anahita"}
        };

      public ActionResult List()
        {
            var data = _datas;
            return View(data);
        }

}
  public class Data
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

 

Now run the application an navigate to List action of Sample Controller:

 

opps!

 

oops!  Remember that you told MVC to use attribute routing, so you should add the attribute routing to List action:

 

        [Route("Sample/List/{Id?}")]
        public ActionResult List()
        {
            var data = _datas;
            return View(data);
        }

 

Now it's ok to get a list of data in list view. to completing our sample add this piece of code in List view to be able to call other actions:

 

@model List<AttributeRouting.Controllers.Data>
@{
    ViewBag.Title = "List";
}

@foreach (var item in Model)
{
    @Html.ActionLink(item.Name, "Data", "Sample", new { id = item.Id }, null)
    <br>
}

 

Now add the Data action with Id parameter:

 

        [Route("Sample/{Id?}")]
        public ActionResult Data(int id)
        {
            var data = _datas.Select(c => c.Id == id);
            return View();
        }

 

If you call this action, Url should be is something like this:   http://localhost:54524/Sample/1

Now add another Data action with a different signature:

 

       [Route("Sample/{Id}/{name?}")]
        public ActionResult Data(int id, string name)
        {
            return View();
        }

 

As you can see the name is in routing but it's optional, if you add another ActionLink in List view: 

 

@foreach (var item2 in Model)
{
    @Html.ActionLink(item2.Name, "Data", "Sample", new { id = item2.Id, name = item2.Name }, null)
}

 

 you can render the second Data action, and it would be something like this in the browser:  http://localhost:54524/Sample/1/Ehsan

Create another action:

 

        [Route("Sample/BlahBlah/{Id}")]
        public ActionResult Another(int id)
        {
            return View();
        }

 

And the related link in list view:

 

@foreach (var item3 in Model)
{
    @Html.ActionLink(item3.Name, "Another", "Sample", new { id = item3.Id }, null)

}   

 

Now if you navigate to the action, it would be: http://localhost:54524/Sample/BlahBlah/1

By the way, you don't need to repeat the controller name in every action, you can use  [RoutePrefix("Sample")] for your controller to be available for all actions:

 

    [RoutePrefix("Sample")]
    public class SampleController : Controller
    {
         …
    }

 

Cheers!

Category: Software

Tags: Asp.Net

comments powered by Disqus