我在我的_Layout.cshtml中定义了这个部分
@RenderSection("Scripts", false)
我可以很容易地从视图中使用它:
@section Scripts {
@*Stuff comes here*@
}
我正在努力解决的问题是如何从局部视图将一些内容注入到这个部分中。
让我们假设这是我的视图页面:
@section Scripts {
<script>
//code comes here
</script>
}
<div>
poo bar poo
</div>
<div>
@Html.Partial("_myPartial")
</div>
我需要在脚本部分中从_myPartial partial视图中注入一些内容。
我该怎么做呢?
普路托的想法比较好:
CustomWebViewPage.cs:
public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel> {
public IHtmlString PartialWithScripts(string partialViewName, object model) {
return Html.Partial(partialViewName: partialViewName, model: model, viewData: new ViewDataDictionary { ["view"] = this, ["html"] = Html });
}
public void RenderScriptsInBasePage(HelperResult scripts) {
var parentView = ViewBag.view as WebPageBase;
var parentHtml = ViewBag.html as HtmlHelper;
parentView.DefineSection("scripts", () => {
parentHtml.ViewContext.Writer.Write(scripts.ToHtmlString());
});
}
}
观点\ web . config:
<pages pageBaseType="Web.Helpers.CustomWebViewPage">
观点:
@PartialWithScripts("_BackendSearchForm")
部分(_BackendSearchForm.cshtml):
@{ RenderScriptsInBasePage(scripts()); }
@helper scripts() {
<script>
//code will be rendered in a "scripts" section of the Layout page
</script>
}
布局页面:
@RenderSection("scripts", required: false)