6

내 응용 프로그램에 다음과 같은 유형의 URL이 있습니다.MVC3에서 두 개의 선택적 매개 변수가 작동하지 않음

로컬 호스트/관리/userdetail/ID

로컬 호스트/관리/userdetail/ID/진정한

로컬 호스트/관리/userdetail/ID/참/성공

여기

는 부울 inSaveAction, 문자열 상태가

[Authorize] 
    public ActionResult UserDetail(string Id, bool inSaveAction, string status) 
    { 
    } 

    [HttpPost, Authorize, ValidateAntiForgeryToken] 
    public ActionResult SaveUserDetail(UserDetailViewModel viewModel) 
    { 
     User userToSave = new User(); 
     AdminService.UpdateUser(userToSave); 
     //This is calling the above function as it sending all 3 params 
     return RedirectToAction("UserDetail", new { Id = viewModel.Id, 
          inSaveAction = true, status = "success" }); 
    } 
경우 아래

를 작동하지 않는 옵션입니다 내 관리 컨트롤러입니다 Global.asax에

routes.MapRoute("UserDetail", 
      "UserDetail/{id}", 
      new 
      { 
       controller = "Admin", 
       action = "UserDetail", 
       id = UrlParameter.Optional 
      } 
     ); 

에서

@Html.ActionLink("DisplayName", "UserDetail", new { id = Model.Id }) 

나는 http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx

어떻게 내가 내 UserDetail 동작에 대한 선택적 매개 변수로 inSaveAction & 상태를 만들 수를 따라?

답변

9

경로 구성에 매개 변수가 없습니다.

@Html.ActionLink("Link", "Index", "Admin", new { id = 1, inSaveAction = true, success = "success" }, null) 

또한 필요합니다에 : (필 Haack의 게시물로) 옵션 다른 매개 변수를이 작품을 만들기 위해 여러 경로

routes.MapRoute("UserDetail-WithStatus", 
       "UserDetail/{id}/{inSaveAction}/{status}", 
       new 
       { 
        controller = "Admin", 
        action = "UserDetail", 
        // nothing optional 
       } 
); 

routes.MapRoute("UserDetail-WithoutStatus", 
       "UserDetail/{id}/{inSaveAction}", 
       new 
       { 
        controller = "Admin", 
        action = "UserDetail", 
        // nothing optional 
       } 
); 

routes.MapRoute("UserDetail-WithoutSaveAction", 
       "UserDetail/{id}", 
       new 
       { 
        controller = "Admin", 
        action = "UserDetail", 
        id = UrlParameter.Optional 
       } 
); 

를 정의한 다음에 링크를 작성해야 선택적 매개 변수를 nullable로 설정하십시오. 그렇지 않으면 id 또는 inSaveAction이 누락 된 경우 예외가 발생합니다.

public ActionResult UserDetail(int? id, bool? inSaveAction, string status) 
{ 

} 
+0

나는 당신이주는 코드를 사용해 보았다. 이것은 또한 작동하지 않습니다. 그것은 행동 방법을 취하지 않습니다. 라우팅 또는 액션 메소드 매개 변수에 문제가 있습니까? –

+0

방금 ​​수정 사항을 게시 했으므로 id 및 inSaveAction을 null로 지정할 수있게해야합니다. 뭐가 문제가되지? 나는 이것을 테스트하고 모든 경로가 작동합니다. – mfanto

+0

감사. 상태 또한 선택적입니다. –

1

도입 된 접근 방식은 here입니다. 이처럼 하나의 경로를 정의 할 수 있습니다.

routes.MapRoute(name: "UserDetail-WithStatus", 
      url: "UserDetail/{id}/{inSaveAction}/{status}", 
      defaults: new 
      { 
       controller = "Admin", 
       action = "UserDetail", 
       // nothing optional 
      }, 
      lookupParameters:new string[] { "id", "inSaveAction", "status" }, 
      routeValueService: new RouteValueService() 

);

관련 문제