2012-02-14 4 views
0

ルートテーブルを定義するときに引数をコントローラに渡す方法はありますか?カスタム引数をmvc3のコントローラに渡す

したがって、同じコントローラを2つ以上の「セクション」に使用することができます。

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 

とコントローラが表示されますindexアクション上記の例で

ように、追加のパラメータによってデータをフィルタリングして表示するルートテーブルで定義されたカスタムの引数を取得し、データがあろう示します私は、これは任意の助けが高く評価され

やや明らかであると思います

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

などのクエリによって返されますか? global.asaxApplication_Startに登録することができ

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

+0

カテゴリ名が一意になる場合は、フィルタとして使用しないでください。 –

答えて

1

カスタムルート書くことができ

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/bizcontactsCategoriesコントローラのIndex作用をヒットし、ID = 1
  • http://localhost:7060/homecontactsCategoriesコントローラのIndex作用をヒットし= 3
  • http://localhost:7060/othercontactsCategoriesコントローラとパスのIndex作用をヒットするIDを通過する通過しますid = 4
+0

はよく見えますが、これはカテゴリコントローラの他のアクションをサポートしますか?例えばsite.com/BizContacts/Edit/4など? – Kumar

+0

@クマー、いいえ、それはしません。しかし、ベースのコンストラクタ呼び出しを変更することによって、サポートに更新することができます。また、 '{id}'ルートパラメータを '{categoryid}'に変更して、URLの最後にあるURLとより明確に区別する必要があるかもしれません。 –

関連する問題