2012-08-10 76 views
0

讓我說我有事件控制器。在控制器中,我有三項操作:與會者,照片和消息。如何創建自定義路由?

如何實現以下路由模式:

  1. www.site.com/event/{eventname}
  2. www.site.com/event/{eventname}/action/
  3. www.site.com/event/{eventname}/action/{actionid}

控制器將被稱爲EventController,Action可以是三個動作(參與者,照片和消息)中的任何一個。例如。

  • www.site.com/event/ - 列表中的所有事件
  • www.site.com/event/autiebirthday/ - 顯示auntibirthday事件,在這個頁面會出現鏈接調用的照片,消息,和與會者的行動。
  • www.site.com/event/autiebirthday/photos/ - 列出阿姨生日活動的所有照片。
  • www.site.com/event/autiebirthday/photos/1 - 顯示ID爲1的照片以及評論。

謝謝。

Rwendi

+0

每個URL映射到哪個控制器/操作? – Faust 2012-08-10 12:17:40

+0

事件名稱是操作所需的參數嗎? – 2012-08-10 12:27:36

+0

補充的例子,希望這個澄清的事情。 – RWendi 2012-08-10 12:28:32

回答

2

路由表:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(
     "EventHome", // Route name 
     "event/{eventName}/{action}/{id}", // URL with parameters 
     new { controller = "Event", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
    ); 

    routes.MapRoute(
     "Default", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
    ); 
} 

控制器:

public class EventController : Controller 
{ 
    public ActionResult Index(string eventName) 
    { 
     ViewBag.EventName = eventName; 

     return View(); 
    } 

    public ActionResult Photos(int? id) 
    { 
     ViewBag.Id = id; 

     return View(); 
    } 
} 

否我簡單地使用ViewBag爲了測試路線工作。您應該自然而然地使用適當的數據源進行生產。

0

這不是很清楚,我的網址應該叫什麼,但我認爲這應該這樣做

routes.MapRoute("", "event/{eventname}", new { controller = "Event", action = "Messages" }); 
routes.MapRoute("", "event/{eventname}/action/{actionid}", new { controller = "Event", action = "Messages", actionId = UrlParameter.Optional });