2012-09-10 2 views
1

MVC 4.0을 사용 중이고 각 컨트롤러에 대한 경로를 추가하려고합니다.하나 이상의 컨트롤러를 라우팅하는 MVC

음, 내 첫 컨트롤러의 이름은 CustomersController입니다. 추가 내가 을 한 경로는 다음과 같습니다 나는 응용 프로그램을 실행하고 때

routes.MapRoute(
     name: "Customer", 
     url: "{controller}/{action}/{IdCustomer}", 
     defaults: new { controller = "Customers", action = "Index", IdCustomer = UrlParameter.Optional } 
    ); 

, 내가 색인 페이지에서 다음 링크 (목록) 얻을 :

http://localhost:6838/Customers/Create/5 
http://localhost:6838/Customers/Edit/5 
http://localhost:6838/Customers/Details/5 
http://localhost:6838/Customers/Delete/5 

확인, 좋은! 그것은 내가 찾고있는 것이지만, 이제는 내 문제를 시작하십시오. 나는 ItemsController라는 또 다른 컨트롤러, 추가 (동일한 액션을을 - 생성/편집/세부/삭제) 나는이 같은 경로를 추가하려고 :

routes.MapRoute(
     name: "Item", 
     url: "{controller}/{action}/{IdItem}", 
     defaults: new { controller = "Items", action = "Index", IdItem = UrlParameter.Optional } 
    ); 

을하지만 지금은 결과가 다르다 ... 내가 무엇입니까 다음 링크 : 왜

http://localhost:6838/Items/Create?IdItem=1 
    http://localhost:6838/Items/Edit?IdItem=1 
    http://localhost:6838/Items/Detail?IdItem=1 
    http://localhost:6838/Items/Delete?IdItem=1 

는 왜 ..?이 작동하지 않습니다 '(이 새로운 하나 를 첫 번째 경로 만 일하고 아니에요 왜 그냥!

안부를 추가 단

+1

경로가 너무 일반적입니다. 이 행동이'Customers' &'Items' (id 이름에 따라 다름)에 특정 할 때 왜 아직도'{controller}'를 사용하고 있습니까? 'Customers/{action}/{IdCustomer}'또는'Items/{action}/{IdItem}'을 사용해야합니다. URL 생성은 순차적 테스트임을 기억하십시오. 파서가 사용할 첫 번째로 일치하는 URL입니다 (이 경우 고객 URL이 사용됩니다). –

+0

나는 처음으로 노선을 사용하고 있습니다. 전에는 사용한 적이 없었습니다. 당신이 의미하는 바를 이해하는 것은 나에게 복잡합니다. – Dan

+0

이제 이해했습니다 ... 감사합니다. @BradChristie – Dan

답변

2

내 대답의 개요를 알려면 경로가 너무 모호합니다. 더 나은 결과를 얻으려면 더 구체적이어야합니다 (특히 경로를 이름으로 사용하지 않는 경우). 나는 다음과 같이 갈 것이다 :

routes.MapRoute(
    name: "Customers", 
    url: "Customers", 
    defaults: new { controller = "Customers", action = "Index" } 
); 
routes.MapRoute(
    name: "CustomerDetails", 
    url: "Customer/{IdCustomer}", 
    defaults: new { controller = "Customers", action = "Details", IdItem = UrlParameter.Optional } 
); 
routes.MapRoute(
    name: "CustomerEdit", 
    url: "Customer/{IdCustomer}", 
    defaults: new { controller = "Customers", action = "Edit", IdItem = UrlParameter.Optional } 
); 
/* and so on (then move on to Items) */ 

지금 당신이 이름을 참조하고 또한 일반적으로 (행동과 컨트롤러 세부 사항과 같은)를 제공하는 초보 많은 정보를 제거 할 수 있습니다. 또한 라우트 이름이 명시된 컨트롤러/조치가 아닌 링크를 쉽게 업데이트합니다.

@Html.RouteLink("Edit Customer", "CustomerEdit", new { IdCustomer = model.Id }); 

이제 다른 지역에이를 만들거나 다른 컨트롤러 경로를 정의하고 모든 RouteLinks이 동일하게 유지 할 수 변경하여 나중에 처리 할 수 ​​있습니다.

관련 문제