Siva P
Siva P

Reputation: 109

Implementing Routes for dynamic actions in MVC 4.0

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?

Upvotes: 3

Views: 1055

Answers (2)

vinayak hegde
vinayak hegde

Reputation: 2222

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"}
 );

Upvotes: 0

Carl
Carl

Reputation: 2295

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

Upvotes: 4

Related Questions