[英]Add @RenderSection to html helper
我需要將代碼添加到我的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));
}
@RenderSection
是服務器生成的代碼片段。 也就是說,當視圖由Razor引擎呈現時,它將@
s和其他特殊的Razor標記內容視為要解析的代碼片段。
當你寫類似
buttonRow.InnerHtml = "@RenderSection('ButtonRow', false)";
您只需將原始字符串寫入HTML,Razor不會解析該字符串。
您可以在布局頁面外部渲染部分,如下所示:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.