如何将HTML内容传递到MVC-Razor中的部分视图,就像"for"块一样

Ach*_*les 13 asp.net-mvc partial-views razor asp.net-mvc-3

我在我的应用程序中使用Chromatron主题作为管理面板.有一个侧边栏小工具有HTML内容和一些CSS技巧,它可以显示完全不同.

<section class="sidebar nested">
    <h2>Nested Section</h2>
    <p>Lorem ipsum dolor sit amet, conse ctetur adipiscing elit. Maec enas id augue ac metu aliquam.</p>
    <p>Sed pharetra placerat est suscipit sagittis. Phasellus <a href="#">aliquam</a> males uada blandit. Donec adipiscing sem erat.</p>
</section>
Run Code Online (Sandbox Code Playgroud)

我希望有一个像这样使用的部分视图:

@Html.Partial("Path/To/Partial/View"){
    <h2>Nested Section</h2>
    <p>Lorem ipsum dolor sit amet, conse ctetur adipiscing elit. Maec enas id augue ac metu aliquam.</p>
    <p>Sed pharetra placerat est suscipit sagittis. Phasellus <a href="#">aliquam</a> males uada blandit. Donec adipiscing sem erat.</p>
}
Run Code Online (Sandbox Code Playgroud)

TBH,我想拥有像@for(...){ }块一样的功能.这是剃刀的可能吗?

jwi*_*ize 24

我遇到了同样的困境.尝试使用Func属性创建viewmodel类型,然后将html作为委托传递.

public class ContainerViewModel
{
    public String Caption { get; set; }
    public String Name { get; set; }
    public Int32 Width { get; set; }
    public Func<object, IHtmlString> Content { get; set; }
}

@Html.Partial("Container", new ContainerViewModel()
{
    Name = "test",
    Caption = "Test container",
    Content =  
    @<text>
       <h1>Hello World</h1>
    </text>,
    Width = 600
})
Run Code Online (Sandbox Code Playgroud)

你可以在你的部分中这样称呼它.

@Model.Content(null)
Run Code Online (Sandbox Code Playgroud)

希望这对你有用.

它的工作原理是因为@ ...语法为你创建了一个HtmlHelper,它使用了一个Model(你在这里声明为type object,并传递null给它),然后返回一个IHtmlString.

如果在内容中使用@ Html.BeginForm,则BEWARE表单值似乎不会发布到服务器.

因此,将表单包裹在容器周围.

  • 我喜欢这个解决方案,但是 &lt;dynamic, ... 感觉很脏,所以我做了一些戳。事实证明,您正在创建一个隐式的小 HtmlHelper,它采用一个模型,因此 Func 的输入 arg 的类型是您喜欢的任何类型(如果需要,则为对象),并且返回类型始终为 IHtmlString。编辑答案以反映这一点。完美运行! (2认同)