You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:.NET Core中RenderSection条件调用报错问题

.NET Core中RenderSection条件调用异常问题排查

问题场景

我在.NET Core项目里遇到了RenderSection的使用异常:在_layout.cshtml中通过条件判断调用RenderSection,代码如下,而index.cshtml里已经定义了两个section。运行IIS时出现报错,但直接单独写@RenderSection("one", false)却能正常工作,请问我的代码哪里有问题?

_layout.cshtml 代码:

@{ Boolean Yes=true; if (Yes == true) { RenderSection("one", false); } else { RenderSection("two", false); } }

index.cshtml 代码:

@section one{ 1111111111111111111111111111111 }
@section two{ 2222222222222222222222222222222 }

问题原因

这是Razor视图的一个常见误区:RenderSection方法返回的是IHtmlContent对象,但在代码块中直接调用它时,如果不用@符号输出,Razor不会把这个对象的内容渲染到页面上。你当前的代码只是调用了方法,但没有将其输出到响应流中,这就导致视图引擎无法正确识别并渲染section内容,进而引发报错。

而单独写@RenderSection("one", false)能正常工作,正是因为@符号告诉Razor要把这个方法返回的内容输出到页面上。

解决方案

只需要在条件判断里的RenderSection调用前加上@符号,让Razor输出该方法返回的内容即可:

@{ Boolean Yes=true; if (Yes == true) { @RenderSection("one", false); } else { @RenderSection("two", false); } }

这样修改后,视图引擎就能正确渲染对应的section内容,不会再出现报错了。

内容的提问来源于stack exchange,提问作者Melon NG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:44:39