我在我的_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视图中注入一些内容。

我该怎么做呢?


当前回答

我们看待网络的方式有一个根本性的缺陷,尤其是在使用MVC的时候。缺陷在于JavaScript在某种程度上是视图的责任。视图是视图,JavaScript(行为或其他)是JavaScript。在Silverlight和WPF的MVVM模式中,我们面临着“视图优先”或“模型优先”的问题。在MVC中,我们应该总是尝试从模型的角度进行推理,而JavaScript在很多方面都是这个模型的一部分。

我建议使用AMD模式(我自己喜欢RequireJS)。在模块中分离你的JavaScript,定义你的功能,从JavaScript中钩子到你的html,而不是依赖于一个视图来加载JavaScript。这将清理您的代码,分离您的关注点,并使生活变得更简单。

其他回答

我能想到的第一个解决方案是使用ViewBag来存储必须呈现的值。

我从来没有试过,如果这个工作从一个局部的观点,但它应该在我看来。

你可以选择使用你的文件夹/索引。CSHTML作为母版,然后添加节脚本。然后,在你的布局中,你有:

@RenderSection("scripts", required: false) 

和index.cshtml:

@section scripts{
     @Scripts.Render("~/Scripts/file.js")
}

它会在所有的partialviews上工作。这对我很有用

普路托的想法比较好:

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)

遵循不引人注目的原则,“_myPartial”并不完全需要将内容直接注入脚本部分。您可以将这些部分视图脚本添加到单独的.js文件中,并从父视图中将它们引用到@scripts部分。

section不能在局部视图中工作,这是设计的。您可以使用一些自定义助手来实现类似的行为,但老实说,包含必要的脚本是视图的责任,而不是部分的责任。我建议使用主视图的@scripts部分来实现这一点,而不用担心脚本的部分。