2011-01-03 3 views
19

ASP.NET MVC의 작업에 여러 매개 변수를 보내고 싶습니다. 나는 또한 다음과 같이 URL을 싶습니다ASP.NET MVC의 작업에 여러 매개 변수 보내기

http://example.com/products/item/2 

대신 :

:

http://example.com/products/item.aspx?id=2 

나뿐만 아니라 보낸 사람에 대해 동일한 작업을 수행하고 싶습니다를, 여기에 현재의 URL입니다

http://example.com/products/item.aspx?id=2&sender=1 

ASP.NET MVC에서 C#으로 어떻게 둘 다 수행합니까?

답변

26

쿼리 문자열에 항목을 전달하는 것이 좋습니다. 매우 쉽습니다. 단순히 일치하는 이름으로 추가 매개 변수를 사용하는 작업 방법을 변경 :

// Products/Item.aspx?id=2 or Products/Item/2 
public ActionResult Item(int id) { } 

이 될 것입니다 :

// Products/Item.aspx?id=2&sender=1 or Products/Item/2?sender=1 
public ActionResult Item(int id, int sender) { } 

ASP.NET MVC는 당신을 위해 모든 것을 배선의 일을 할 것입니다. 클린 찾고 URL을 원하는 경우

, 당신은 단순히 Global.asax.cs에 새로운 경로를 추가해야합니다

// will allow for Products/Item/2/1 
routes.MapRoute(
     "ItemDetailsWithSender", 
     "Products/Item/{id}/{sender}", 
     new { controller = "Products", action = "Item" } 
); 
+0

의 URL 형식은 무엇인가? – Reza

+0

global.asax에서 경로에 대한 적절한 정의를 설정하는 것을 잊지 마십시오. –

+0

@Reza - URL에 코드로 주석을 추가했습니다. 보다 깔끔한 URL을 원한다면 global.asax.cs에 대한 맞춤 경로를 추가해야합니다. –

4

당신이 예를 들어 어떤 경로 규칙을 사용할 수 있습니다

{controller}/{action}/{param1}/{param2} 

:baseUrl?param1=1&param2=2

등의 매개 변수를 사용하고 this link을 확인해 주시면 도움이되기를 바랍니다.

12

예쁜 URL을 원한다면 global.asax.cs에 다음을 추가하십시오.

routes.MapRoute("ProductIDs", 
    "Products/item/{id}", 
    new { controller = Products, action = showItem, id="" } 
    new { id = @"\d+" } 
); 

routes.MapRoute("ProductIDWithSender", 
    "Products/item/{sender}/{id}/", 
    new { controller = Products, action = showItem, id="" sender="" } 
    new { id = @"\d+", [email protected]"[0-9]" } //constraint 
); 

그리고 사용하기 위해 필요한 조치 :

public ActionResult showItem(int id) 
{ 
    //view stuff here. 
} 

public ActionResult showItem(int id, int sender) 
{ 
    //view stuff here 
}