2011-02-10 225 views
23

我認爲這將是直線前進,但我設法軟管它一些如何。如果我想將URL參數傳遞給另一個操作,我是否必須爲此創建一個新的路由?ASP.Net MVC如何通過使用Html.RenderAction網址參數的ChildAction

控制器

[ChildActionOnly] 
    public ActionResult ContentSection(string sectionAlias, string mvcController, string mvcAction = null) 

視圖

@Html.RenderAction("ContentSection", "Portal", new {sectionAlias = "TermsAndConditions", mvcController = "Portal", mvcAction = "ChoosePayment"}) 

錯誤

CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments 

回答

30

這裏的問題是,

@Html.RenderAction("ContentSection", "Portal", new {sectionAlias = "TermsAndConditions", mvcController = "Portal", mvcAction = "ChoosePayment"}) 

是對相當於

<%= Html.RenderAction("ContentSection", "Portal", new {sectionAlias = "TermsAndConditions", mvcController = "Portal", mvcAction = "ChoosePayment"}) %> 

在所述Web表單ViewEngine(其也是相同的一個Response.Write)。由於RenderAction回報void,你不能Response.Write它。你想要做的是這樣的:

@{ 
    Html.RenderAction("ContentSection", "Portal", new {sectionAlias = "TermsAndConditions", mvcController = "Portal", mvcAction = "ChoosePayment"}); 
} 

@{ }語法表示在Razor視圖引擎代碼塊,下面的的Web表單ViewEngine這是等價的:

<% Html.RenderAction("ContentSection", "Portal", new {sectionAlias = "TermsAndConditions", mvcController = "Portal", mvcAction = "ChoosePayment"}); %> 
+9

或者你可以撥打@ Html.Action(...),而不是爲了稱呼其爲返回的內容的方法(如果你不喜歡使用大括號等) – 2011-02-11 00:33:38

11

簡短的回答將是:使用@ Html.Action()。

@Html.Action("ContentSection", "Portal", new {sectionAlias = "Terms", ...}) 

long answer已經由Nathan Anderson給出。

P.S.信用這個答案真的去美甲詹姆斯,誰張貼在彌敦道的回答評論,但我發現它如此簡單和有價值的,我認爲它應該是一個單獨的答案。