ASP.Net MVC如何使用Html.RenderAction传递URL参数到ChildAction?

35
我原本以为这很简单,但不知怎么搞砸了。如果我想将URL参数传递给另一个操作,我是否需要为此创建一个新路由?
控制器
[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
2个回答

46

问题在于

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

这句话的意思是

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

在WebForms的ViewEngine中(也是与Response.Write相同),由于RenderAction返回void,所以您无法对其进行Response.Write。您想要做的是这样的:

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

@{ }语法表示Razor视图引擎中的代码块,相当于Webforms ViewEngine中的以下内容:

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

13
或者你可以调用 @Html.Action(...) ,以方法的形式返回你的内容(如果你不喜欢使用花括号等)。 - James Nail
谢谢,我通过阅读另一篇类似的帖子弄明白了。谢谢!我想这之前也曾让我困扰过。 - JBeckton
1
是的,这确实是一篇写得很好的答案。谢谢Nathan!也感谢James Nail。你的提示也很有价值。 - Oliver

16

简短的回答是使用如下的@Html.Action()

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

长答案已经由Nathan Anderson提供。

P.S. 这个答案的真正功劳应该归功于James Nail,他在Nathan的答案评论中发布了它,但我觉得它非常简单和有价值,所以我认为它应该是一个独立的答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接