【问题标题】:How can I pass HTML content to a Partial View in MVC-Razor like a "for" block如何将 HTML 内容传递给 MVC-Razor 中的部分视图,如“for”块
【发布时间】:2012-03-24 05:25:52
【问题描述】:

我在我的应用程序中使用 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>

我想要一个像这样使用的局部视图:

@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(...){ } 块中那样的功能。 这在 Razor 中可行吗?

【问题讨论】:

  • 不知道是不是你想要的,不过看看:lostechies.com/hugobonacci/2011/07/11/templates-with-razor
  • 谢谢费利佩。但这不是我想要的,或者我无法让它工作。我需要与for 块相同的功能。我想要一个尾随块,我可以在其中插入其他 @ razor 指令或 HTML 内容;就像for 块...
  • 我正在尝试做同样的事情;见我的very similar SO question。我发现的最接近的是@FelipeOriani 提到的帖子。 HtmlHelper 扩展方法也可以,但我还没有想出将它用作视图或部分视图的 HTML 存储。但是,实际上,我只需要放弃辅助函数语法的括号块语法。

标签: asp.net-mvc asp.net-mvc-3 razor partial-views


【解决方案1】:

您似乎需要某种 htmlhelper 函数来生成该内容。您是否考虑过将其实现为助手而不是局部视图?

【讨论】:

  • 我已经研究过“内联助手”,它可以完成这项工作;实际上有几种方法可以将内容传递给占位符;但我认为如果我可以使用上面显示的符号,我的 HTML 代码看起来会更清晰。
【解决方案2】:

我也有同样的困境。尝试使用 Func 属性创建视图模型类型,然后将 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
})

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

@Model.Content(null)

如果你想花哨,可以添加这个扩展方法。

public static class PartialExtensions
{
    public static IHtmlString Display<T>
        (this T model, Expression<Func<T, Func<Object, IHtmlString>>> content) 
    {
        var compiled = content.Compile();
        return compiled.Invoke(model).Invoke(null);
    }
}

然后,任何时候你使用这个模式,你都可以在你的部分(未完全测试)中这样调用它。

@model ContainerViewModel
@Model.Display(m => m.Content)  // Use delegate property

希望这对你有用。

它之所以有效,是因为 @... 语法为您创建了一个小 HtmlHelper,它使用一个模型(您在此处将其声明为类型 object,并为 null 传递),并返回一个 IHtmlString

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

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

【讨论】:

  • 我喜欢这个解决方案,但是
  • 这个解决方案绝对是绝妙的!我可以使用周围的 HTML 内容创建我的小部件/部分,并使用此方法将内容注入其中。它很干净而且效果很好!谢谢!
  • 优秀的解决方案,对子操作没有任何作用,这可以完美地作为参数,谢谢
猜你喜欢
  • 2019-11-04
  • 1970-01-01
  • 2017-02-16
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
相关资源
最近更新 更多