2012-02-14 3 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 

컨트롤러 도시한다 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) 
    { 
     ... 
    } 
} 

을 :

,210
  • http://localhost:7060/bizcontactsCategories 컨트롤러 Index 작용 치고 ID = 1
  • http://localhost:7060/homecontactsCategories 컨트롤러 Index 작용 치고 이드 = 3
  • http://localhost:7060/othercontactsCategories 컨트롤러 Index 동작을 치고 합격 합격 합격 id = 4
+0

이 좋을 것입니다.이 기능은 카테고리 컨트롤러에서 다른 작업을 지원합니까? 예 : site.com/BizContacts/Edit/4 등? – Kumar

+0

@Kumar, 아니, 그렇지 않을 것이다. 그러나 기본 생성자 호출을 변경하여 지원하도록 업데이트 할 수 있습니다. 또한 URL의 끝에있는 URL과 URL을 더 명확하게 구분하기 위해'{id}'경로 매개 변수를'{categoryid} '로 변경해야 할 수도 있습니다. –