2010-10-26 15 views
0

我想在我的母版頁上使用MVC2在VS 2010中使用Html.RenderAction()呈現局部視圖。這裏是我的RenderAction()調用:ASP.NET MVC2 - 如何使用RenderAction()調用另一個控制器並將參數傳遞給該控制器?

  <% Html.RenderAction(
        "Menu", 
        "Navigation", 
        new 
        { 
         currentAction = ViewContext.RouteData.Values["action"], 
         currentController = ViewContext.RouteData.Values["controller"] 
        } 
      ); %> 

然而,當它的導航控制器的構造函數,它總是命中是不帶任何參數定義構造函數。

public class NavigationController : Controller 
{ 
    public NavigationViewModel navigationViewModel { get; set; } 

    public NavigationController() 
    { 
     -snip- 
    } 

    public NavigationController(string currentAction, string currentController) 
    { 
     -snip- 
    } 

    [ChildActionOnly] 
    public ViewResult Menu() 
    { 
     return View(this.navigationViewModel); 
    } 
} 

在我看到的所有例子中,這是如何使用RenderAction()調用傳遞參數。如果我刪除沒有定義參數的構造函數,除了抱怨之外,我不會收到任何錯誤消息。

我怎樣才能調用具有兩個參數定義的構造函數?我希望在構建菜單時能夠與currentAction和currentController進行比較,以正確突出顯示用戶當前所在的部分。

+0

MVC總是調用無參數的構造函數內部,除非你正在做一些花哨的依賴注入。 – 2010-10-26 15:17:21

回答

5

根據您的示例,您將參數傳遞給動作,而不是控制器構造函數。

因此,實際上,我認爲你應該做的是更多像這樣的

public class NavigationController 
{ 
    [ChildActionOnly] 
    public ViewResult Menu(string currentAction, string currentController) 
    { 
     var navigationViewModel = new NavigationViewModel(); 

     // delegates the actual highlighing to your view model 
     navigationViewModel.Highlight(currentAction, currentController); 

     return View(navigationViewModel); 
    } 
} 
+0

啊哈!你是對的,謝謝你,先生! – Sgraffite 2010-10-26 16:29:22

相關問題