1

我需要将代码添加到我的 html 助手中以生成与以下 html 等效的内容:

<div id="buttonrow">@RenderSection("ButtonRow", false)</div>

这可能吗?

这行不通...

public static MvcHtmlString ButtonRow(this HtmlHelper helper)
{  
TagBuilder buttonRow = new TagBuilder("div");
buttonRow.GenerateId("buttonRow");
buttonRow.InnerHtml = "@RenderSection('ButtonRow', false)";

return MvcHtmlString.Create(buttonRow.ToString(TagRenderMode.Normal));
}
4

2 回答 2

1

@RenderSection是服务器生成的代码片段。也就是说,当 Razor 引擎渲染视图时,它将@s 和其他特殊的 Razor 标记内容视为要解析的代码片段。

当你写类似的东西时

buttonRow.InnerHtml = "@RenderSection('ButtonRow', false)";

您只需将原始字符串写入 HTML,Razor 不会解析的字符串。

于 2012-12-13T11:59:47.703 回答
1

您在布局页面之外呈现一个部分,如下所示:

public static IHtmlString RenderSectionCustom(this HtmlHelper html)
{
    WebViewPage page = html.ViewDataContainer as WebViewPage;
    var section = page.RenderSection("CustomTop", false);
    return section == null ? MvcHtmlString.Empty : MvcHtmlString.Create(section.ToHtmlString());
}

public static IHtmlString DefineSectionCustom(this HtmlHelper html)
{
    WebViewPage page = html.ViewDataContainer as WebViewPage;

    page.DefineSection("CustomTop", () =>
    {
        page.Write(MvcHtmlString.Create(" hello world (custom top section from HTML HELPER)!"));
    });

    return MvcHtmlString.Empty;
}
于 2017-09-13T13:54:42.977 回答