Implementing Routes for dynamic actions in MVC 4.0

落花浮王杯 提交于 2019-12-10 09:46:32

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/25765196/implementing-routes-for-dynamic-actions-in-mvc-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!