如何传递HTML内容在MVC-剃刀状的局部视图A"为"块 [英] How can I pass HTML content to a Partial View in MVC-Razor like a "for" block

查看:143
本文介绍了如何传递HTML内容在MVC-剃刀状的局部视图A"为"块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是彩色显象管的主题在我的应用程序的管理面板。有一个具有HTML内容和一个小窍门CSS可以证明完全不同的一个边栏小工具。

I'm using Chromatron theme for an admin panel in my application. There is a sidebar gadget that has HTML content and with a little CSS trick it can be shown completely different.

<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>

我想有这样使用的局部视图:

I want to have a Partial View that is used like this:

@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>
}

TBH,我想有功能,例如我有一个 @for(...){} 块。
这是可能的剃刀?

TBH, I want to have functionality like I have in a @for(...){ } block. Is this possible in Razor?

推荐答案

我有同样的困境。尝试用Func键属性创建一个视图模型类型,然后通过HTML作为代表。

I was having the same dilemma. Try creating a viewmodel type with a Func property and then pass the html as delegate.

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
})

您可以在您的局部称呼它。

You can call it like this in your partial.

@Model.Content(null)

希望这对你的作品。

Hope this works for you.

它的工作原理,因为@ ...语法为您创建一个小的HtmlHelper消耗模型(这你在这里声明类型对象,并通过的),并返回一个 IHtmlString

It works because the @... syntax creates a little HtmlHelper for you that consumes a Model (which you're declaring here as type object, and passing null for), and returns an IHtmlString.

当心似乎形式值不张贴到服务器,如果@ Html.BeginForm在内容使用。

BEWARE form values don't seem to post to the server if @Html.BeginForm is used in the content.

因此​​,包装容器周围的形式。

Therefore, wrap your form around the container.

这篇关于如何传递HTML内容在MVC-剃刀状的局部视图A&QUOT;为&QUOT;块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆