我在我的_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视图中注入一些内容。
我该怎么做呢?
我解决这个完全不同的路线(因为我很着急,不想实现一个新的HtmlHelper):
我用一个大的if-else语句包装了我的Partial View:
@if ((bool)ViewData["ShouldRenderScripts"] == true){
// Scripts
}else{
// Html
}
然后,我用自定义ViewData调用了两次Partial:
@Html.Partial("MyPartialView", Model,
new ViewDataDictionary { { "ShouldRenderScripts", false } })
@section scripts{
@Html.Partial("MyPartialView", Model,
new ViewDataDictionary { { "ShouldRenderScripts", true } })
}
我有一个类似的问题,我有一个母版页如下:
@section Scripts {
<script>
$(document).ready(function () {
...
});
</script>
}
...
@Html.Partial("_Charts", Model)
但是部分视图依赖于脚本部分中的一些JavaScript。我通过将部分视图编码为JSON来解决这个问题,将其加载到JavaScript变量中,然后使用它来填充一个div,因此:
@{
var partial = Html.Raw(Json.Encode(new { html = Html.Partial("_Charts", Model).ToString() }));
}
@section Scripts {
<script>
$(document).ready(function () {
...
var partial = @partial;
$('#partial').html(partial.html);
});
</script>
}
<div id="partial"></div>
有一种方法可以在局部视图中插入部分,尽管它并不漂亮。你需要从父视图中访问两个变量。由于部分视图的部分目的就是创建该section,因此需要这些变量是有意义的。
下面是在局部视图中插入一个section的样子:
@model KeyValuePair<WebPageBase, HtmlHelper>
@{
Model.Key.DefineSection("SectionNameGoesHere", () =>
{
Model.Value.ViewContext.Writer.Write("Test");
});
}
在页面中插入部分视图…
@Html.Partial(new KeyValuePair<WebPageBase, HtmlHelper>(this, Html))
您还可以使用此技术在任何类中以编程方式定义节的内容。
享受吧!