渲染部分给我奇怪的超载错误?

我创建了一个名为 _ Test.cshtml的测试部分页面,并将其放在将要调用它的视图所在的目录中,如下所示:

<div>hi</div>

在调用 cshtml 视图中,我简单地输入:

@Html.RenderPartial("_Test")

这就给了我一个错误:

CS1502: 最佳重载方法 与... 相匹配 ‘ System.Web.WebPages. WebPageExecutingBase. Write (System.Web.WebPages. HelperResult)’ 有一些无效的论点

我也尝试了完整的路径,得到了相同的结果。

我很困惑为什么会这样,我想我错过了一些简单的东西?

27484 次浏览

You are getting this error because Html.RenderXXX helpers return void - they have nothing to return because they are writing stuff directly* to response. You should use them like this:

@{ Html.RenderPartial("_Test"); }

There is also Html.Partial helper, which will work with your syntax, but I'd not recommend using it unless you have to, because of performance (it first composes given partial view into string, and then parent view puts it into response*).

* this is not entirely true, they are actually being rendered into ViewContext.Writer and once whole page is rendered and composed, the whole thing goes to response