我在我的_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)

其他回答

我的解决方案是从布局页面加载脚本。然后在javacript中,检查局部视图中是否存在一个元素。如果元素存在,javascript就知道该部分已被包含。

$(document).ready(function () {
    var joinButton = $("#join");
    if (joinButton.length != 0) {
        // the partial is present
        // execute the relevant code
    }
});

如果你确实有合法的需要从一个部分运行一些js,这里是你可以做到的,jQuery是必需的:

<script type="text/javascript">        
    function scriptToExecute()
    {
        //The script you want to execute when page is ready.           
    }

    function runWhenReady()
    {
        if (window.$)
            scriptToExecute();                                   
        else
            setTimeout(runWhenReady, 100);
    }
    runWhenReady();
</script>

OP的目标是将内联脚本定义到他的Partial View中,我假设这个脚本仅特定于该Partial View,并将该块包含到他的脚本部分中。

我明白他想要局部视图是独立的。这个想法类似于使用Angular时的组件。

我的方法是将脚本原样保存在Partial View中。现在的问题是,当调用Partial View时,它可能会在所有其他脚本(通常被添加到布局页面的底部)之前执行脚本。在这种情况下,您只需让Partial View脚本等待其他脚本。有几种方法可以做到这一点。我之前用过的最简单的方法是在body上使用事件。

在我的布局中,我会在底部有这样的东西:

// global scripts
<script src="js/jquery.min.js"></script>
// view scripts
@RenderSection("scripts", false)
// then finally trigger partial view scripts
<script>
  (function(){
    document.querySelector('body').dispatchEvent(new Event('scriptsLoaded'));
  })();
</script>

然后在我的局部视图(在底部):

<script>
  (function(){
    document.querySelector('body').addEventListener('scriptsLoaded', function() {

      // .. do your thing here

    });
  })();
</script>

另一种解决方案是使用堆栈来推送所有脚本,并在最后调用每个脚本。其他解决方案,如前所述,是RequireJS/AMD模式,它也非常有效。

有一种方法可以在局部视图中插入部分,尽管它并不漂亮。你需要从父视图中访问两个变量。由于部分视图的部分目的就是创建该section,因此需要这些变量是有意义的。

下面是在局部视图中插入一个section的样子:

@model KeyValuePair<WebPageBase, HtmlHelper>
@{
    Model.Key.DefineSection("SectionNameGoesHere", () =>
    {
        Model.Value.ViewContext.Writer.Write("Test");
    });
}

在页面中插入部分视图…

@Html.Partial(new KeyValuePair<WebPageBase, HtmlHelper>(this, Html))

您还可以使用此技术在任何类中以编程方式定义节的内容。

享受吧!

我今天遇到了这个问题。我将添加一个工作区,使用<脚本延迟>,因为我没有看到其他答案提到它。

//on a JS file somewhere (i.e partial-view-caller.js)
(() => <your partial view script>)();

//in your Partial View
<script src="~/partial-view-caller.js" defer></script>

//you can actually just straight call your partial view script living in an external file - I just prefer having an initialization method :)

上面的代码摘自我关于这个问题的一篇文章。