3

Is it possible to define a route in MVC that dynamically resolves the action based on part of the route?

public class PersonalController
{
  public ActionResult FriendGroup()
  {
      //code
  }

  public ActionResult RelativeGroup()
  {
      //code
  }

  public ActionResult GirlFriendGroup()
  {
      //code
  }
}

I want to implement a routing for my Group Action Method below

Url: www.ParlaGroups.com/FriendGroup
     www.ParlaGroups.com/RelativeGroup
     www.ParlaGroups.com/GirlFriendGroup

routes.MapRoute(
    "Friends",
    "/Personal/{Friend}Group",
    new { controller = "Personal", action = "{Friend}Group" }
);
routes.MapRoute(
    "Friends",
    "/Personal/{Relative}Group",
    new { controller = "Personal", action = "{Relative}Group" }
);
routes.MapRoute(
    "Friends",
    "/Personal/{GirlFriend}Group",
    new { controller = "Personal", action = "{GirlFriend}Group" }
);

How can i do the above routing implementation?

tereško
  • 58,060
  • 25
  • 98
  • 150
Siva P
  • 109
  • 1
  • 12
  • This is Routing 101. Please the documentation: http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs – Chris Pratt Sep 10 '14 at 13:08

2 Answers2

4

The following route will allow MVC to determine the ActionResult by using the second part of the Url:

routes.MapRoute(
"Friends",
"Personal/{action}",
new { controller = "Personal" }
);

The following urls will match:

www.ParlaGroups.com/Personal/FriendGroup Where "FriendGroup" is the ActionResult www.ParlaGroups.com/Personal/RelativeGroup Where "RelativeGroup" is the ActionResult www.ParlaGroups.com/Personal/GirlFriendGroup Where "GirlFriendGroup" is the ActionResult

Carl
  • 2,285
  • 1
  • 16
  • 31
  • Ok, I'm no longer clear what you are trying to achieve. You could drop the "Group" from the names of your action result methods and have a route like: `routes.MapRoute( "Friends", "Personal/{action}Group", new { controller = "Personal" } );` – Carl Sep 10 '14 at 12:52
0
public class PersonalController
{
  public ActionResult FriendGroup()
  {
   //code
  }

  public ActionResult RelativeGroup()
  {
   //code
  }

  public ActionResult GirlFriendGroup()
  {
   //code
  }
}

 Url: www.ParlaGroups.com/FriendGroup
      www.ParlaGroups.com/RelativeGroup
      www.ParlaGroups.com/GirlFriendGroup


 routes.MapRoute(
  "Friends",
  "/{action}",
  new { controller = "Personal"}
 );
vinayak hegde
  • 2,117
  • 26
  • 26