javascript 在 .NET MVC 5 中从部分视图添加到脚本包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21827009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:46:37  来源:igfitidea点击:

Adding to script bundle from partial view in .NET MVC 5

javascriptcssasp.net-mvc

提问by The Kaizer

We are making a .Net MVC websolution that is going to be using widgets rendered as HTML.Partials(). We would like to be able for the partial view to add its dependencys in the main page views scripts tags, both css-files as well as javascript files.

我们正在制作一个 .Net MVC websolution,它将使用呈现为 HTML.Partials() 的小部件。我们希望能够让局部视图在主页面视图脚本标签中添加其依赖项,包括 css 文件和 javascript 文件。

Ive been trying with this code in my partial. But the js-file isnt rendered in the layout section of my page. What is wrong?

我一直在尝试使用我的部分代码。但是 js 文件没有在我页面的布局部分呈现。怎么了?

@{

    var bundle = System.Web.Optimization.BundleTable.Bundles.GetRegisteredBundles()
        .Where(b => b.Path == "~/bundles/jquery")
        .First();

    bundle.Include("~/Scripts/addtojquerybundletest.js");
}

回答by The Kaizer

It just seemed to be specific to my jquery bundle. It now works, I have added a widgetspecific bundle where you can add scripts to render in the main layout. The bundle also handles the adding of the same file several times (which can happen if the same widget exists several times on the same page) and only renderes it once. My solution added below, which doesnt seem to be that well documented from the searches Ive done so far.

它似乎特定于我的 jquery 包。它现在可以工作了,我添加了一个特定于小部件的包,您可以在其中添加脚本以在主布局中呈现。该包还多次处理相同文件的添加(如果同一小部件​​在同一页面上多次存在,则可能会发生这种情况)并且只呈现一次。我的解决方案在下面添加,从我迄今为止所做的搜索来看,这似乎没有得到很好的记录。

In BundleConfig.cs:

在 BundleConfig.cs 中:

bundles.Add(new ScriptBundle("~/widgetspecific"));

In _Layout.cshmtl:

在 _Layout.cshmtl 中:

@Scripts.Render("~/widgetspecific")

In Widget.cshtml:

在 Widget.cshtml 中:

@{
    var bundle = System.Web.Optimization.BundleTable.Bundles.GetBundleFor("~/widgetspecific");

    bundle.Include("~/Scripts/andreas.js");
}

Is anyone aware of negative aspects to this solution?

有没有人知道这个解决方案的负面影响?

回答by DigitalFreak

@The Kaizer, For you own answer above. In Widget.cshtml you might want to use

@The Kaizer,对于您自己的上述答案。在 Widget.cshtml 你可能想要使用

var bundle = System.Web.Optimization.BundleTable.Bundles.GetBundleFor("~/widgetspecific");

回答by GTL

You would need to create a new bundle for each widget, otherwise if you re-use the "~/widgetspecific" bundle it will continue to add the scripts from the previous page's widget as you navigate through your site.

您需要为每个小部件创建一个新包,否则如果您重新使用“~/widgetspecific”包,它会在您浏览站点时继续添加来自上一页小部件的脚本。