2012-02-14 167 views
0

有什麼辦法在定義路由表來傳遞參數給控制器?傳遞自定義參數傳遞給控制器​​在MVC3

因此相同的控制器可以被用於兩個或更多個「區段」例如

http://site.com/BizContacts // internal catid = 1 defined in the route   
http://site.com/HomeContacts // internal catid = 3 
http://site.com/OtherContacts // internal catid = 4 

和控制器獲取在路由表中定義的由附加的參數在索引動作將被示出上述例子中以過濾和顯示數據

所以自定義參數,並示出的數據將是通過爲

select * from contacts where cat_id = {argument} // 1 or 3 or 4 

這樣的查詢返回我希望這是有點清晰

任何幫助表示讚賞?

+0

如果類別名稱將是獨一無二的,爲什麼不把它們作爲你的過濾器? – 2012-02-14 23:13:00

回答

1

你可以寫一個自定義路由:

public class MyRoute : Route 
{ 
    private readonly Dictionary<string, string> _slugs; 

    public MyRoute(IDictionary<string, string> slugs) 
     : base(
     "{slug}", 
     new RouteValueDictionary(new 
     { 
      controller = "categories", action = "index" 
     }), 
     new RouteValueDictionary(GetDefaults(slugs)), 
     new MvcRouteHandler() 
    ) 
    { 
     _slugs = new Dictionary<string, string>(
      slugs, 
      StringComparer.OrdinalIgnoreCase 
     ); 
    } 

    private static object GetDefaults(IDictionary<string, string> slugs) 
    { 
     return new { slug = string.Join("|", slugs.Keys) }; 
    } 

    public override RouteData GetRouteData(HttpContextBase httpContext) 
    { 
     var rd = base.GetRouteData(httpContext); 
     if (rd == null) 
     { 
      return null; 
     } 
     var slug = rd.Values["slug"] as string; 
     if (!string.IsNullOrEmpty(slug)) 
     { 
      string id; 
      if (_slugs.TryGetValue(slug, out id)) 
      { 
       rd.Values["id"] = id; 
      } 
     } 
     return rd; 
    } 
} 

可能在Application_Startglobal.asax註冊:

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

    routes.Add(
     "MyRoute", 
     new MyRoute(
      new Dictionary<string, string> 
      { 
       { "BizContacts", "1" }, 
       { "HomeContacts", "3" }, 
       { "OtherContacts", "4" }, 
      } 
     ) 
    ); 

    routes.MapRoute(
     "Default", 
     "{controller}/{action}/{id}", 
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 
} 

最後你可以有你的CategoriesController:

public class CategoriesController : Controller 
{ 
    public ActionResult Index(string id) 
    { 
     ... 
    } 
} 

現在:

  • http://localhost:7060/bizcontacts將擊中Categories控制器的Index動作並傳遞ID = 1
  • http://localhost:7060/homecontacts將擊中Categories控制器的Index動作並傳遞ID = 3
  • http://localhost:7060/othercontacts將擊中Categories控制器的Index動作和傳ID = 4
+0

看起來不錯,這還支持在類別控制器等動作?例如site.com/BizContacts/Edit/4等? – Kumar 2012-02-15 02:48:20

+0

@Kumar,不,它不會。但是您可以通過更改基礎構造函數來更新它以支持。您可能還需要修改'{ID}'路線參數'{}類別ID',以便將其與一個在URL的末尾之間的更清楚地區分。 – 2012-02-15 06:28:31