asp.net-mvc-3 – ASP.Net MVC 3剃刀:部分定义但未呈现错误

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – ASP.Net MVC 3剃刀:部分定义但未呈现错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下布局模板:
  1. <div id="columns" class="@View.LayoutClass">
  2. <div id="mainColWrap">
  3. <div id="mainCol">
  4. @RenderBody()
  5. </div>
  6. </div>
  7. @if (View.ShowLeftCol){
  8. <div id="leftCol">
  9. @RenderSection("LeftCol",required: false)
  10. </div>
  11. }
  12. @if (View.ShowRightCol){
  13. <div id="rightCol">
  14. @RenderSection("RightCol",required: false)
  15. </div>
  16. }
  17. </div>

如果View.ShowLeftCol或View.ShowRightCol设置为false,我得到以下错误

以下部分已定义,但尚未呈现为布局页“〜/ Views / Shared / _Layout.cshtml”:“RightCol”。

我试图有一个单一的布局模板,而不是试图在运行时动态选择一个模板。有没有办法忽略此错误并继续呈现?任何人都可以想到另一种方式实现,这将允许我动态显示/隐藏列与Razor?

谢谢!

解决方法

ASP.net论坛上工作的建议。

基本上,如果我定义@section LeftCol在我的视图模板,但不运行任何调用RenderSection在我的布局中的代码,我得到错误,因为它不会被调用时View.ShowLeftCol为false。建议添加一个else块,并且基本上扔掉LeftCol部分中的任何内容

  1. @if (View.ShowLeftCol)
  2. {
  3. <div id="leftCol">
  4. @RenderSection("LeftCol",false)
  5. </div>
  6. }
  7. else
  8. {
  9. WriteTo(new StringWriter(),RenderSection("LeftCol",false));
  10. }

基于对记忆的关注,我决定测试以下。事实上,它也工作。

  1. @if (showLeft)
  2. {
  3. <section id="leftcol">
  4. <div class="pad">
  5. @RenderSection("LeftColumn",false)
  6. </div>
  7. </section>
  8. }
  9. else
  10. {
  11. WriteTo(TextWriter.Null,RenderSection("LeftColumn",false));
  12. }

另外,在我的页面的顶部,这是我的新逻辑为showLeft / showRight:

  1. bool showLeft = IsSectionDefined("LeftColumn");
  2. bool showRight = IsSectionDefined("RightColumn");
  3. bool? hideLeft = (bool?)ViewBag.HideLeft;
  4. bool? hideRight = (bool?)ViewBag.HideRight;
  5. if (hideLeft.HasValue && hideLeft.Value == true) { showLeft = false; }
  6. if (hideRight.HasValue && hideRight.Value == true) { showRight = false; }

有人说它不为他们工作,但它的工作方式像我一样的魅力。

猜你在找的asp.Net相关文章