微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

剃刀视图中的动态定义的内容部分

如何解决剃刀视图中的动态定义的内容部分

|| 我试图实现一个想法,我必须允许为我的MVC 3 Razor网站动态生成用户定义的部分。 模板看起来像这样
<div class=\"sidebar\">
     @RenderSection(\"Sidebar\",false)
</div>
<div class=\"content\">
     @RenderSection(\"MainContent\",false)
     @RenderBody()
</div>
使用以下代码添加视图会给我我期望的结果
Definesection(\"MainContent\",() =>
{
    this.Write(\"Main Content\");
});
Definesection(\"Sidebar\",() =>
{
    this.Write(\"Test Content\");
});
输出
<div class=\"sidebar\">Test Content </div>
<div class=\"content\">Main Content <p>Rendered body from view</p></div>
看着这个,创建模型似乎很容易
Dictionary<SectionName,Dictionary<ControlName,Model>>
var sectionControls = new Dictionary<string,Dictionary<string,dynamic>>();
        sectionControls.Add(\"MainContent\",new Dictionary<string,dynamic>()
        { 
            {\"_shoppingCart\",cart}
        });
        sectionControls.Add(\"Sidebar\",dynamic>() 
        { 
            { \"_headingImage\",pageModel.headingImage },{ \"_sideNav\",null }
        });
        pageModel.SectionControls = sectionControls;
因此,上面的代码声明了两个模板部分(带有购物车的\“ MainContent \”和带有图像和导航的\“ Sidebar \”)。 所以现在我的视图包含代码来像这样渲染输出
foreach(keyvaluePair<string,dynamic>> section in Model.SectionControls)
    {
        Definesection(section.Key,() =>
        {
            foreach (keyvaluePair<string,dynamic> control in section.Value)
            {
                RenderPartialExtensions.RenderPartial(Html,control.Key,control.Value);
            }
        });
  }
现在,当我运行此代码时,两个部分都包含相同的内容!单步执行代码显示加载路径如下 动作返回,上面的代码在View中运行,LayoutTemlpate开始加载。当在布局模板中为这两个部分调用RenderSection时,视图将再次运行!在我看来,甚至更奇怪的是,最终结果是\“ headingImage \”和\“ SideNav \”都出现在补充工具栏和MainContent部分中。 MainContent部分不包含购物车,它包含侧边栏部分的副本。
<div class=\"sidebar\">
<h2><img alt=\" \" src=\"...\"></h2>
..nav..
</div>
<div class=\"content\">
<h2><img alt=\" \" src=\"...\"></h2>
..nav..
<p>Rendered body from view</p>
</div>
注释掉Controller中两个节定义之一,会使另一个成为唯一项(但仍重复!) 是否有人曾遇到过此问题,或者知道什么限制可能导致此行为? 编辑:优秀。也感谢您的联系!我对使用剃须刀支持的新版剃刀感到很痛苦。     

解决方法

        您的lambda表达式共享相同的
section
变量。 当调用任一lambda时,变量的当前值是最后一部分。 您需要在循环中声明一个单独的变量。
foreach(KeyValuePair<string,Dictionary<string,dynamic>> dontUse in Model.SectionControls)
{
    var section = dontUse;

    DefineSection(section.Key,() =>
    {
        foreach (KeyValuePair<string,dynamic> control in section.Value)
        {
            RenderPartialExtensions.RenderPartial(Html,control.Key,control.Value);
        }
    });
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。