ASP.NET MVC在局部视图中加载脚本 [英] ASP.NET MVC Loading scripts in partial views

查看:225
本文介绍了ASP.NET MVC在局部视图中加载脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的整个网站都是Ajax网站,因此我的所有视图(除Layout之外)都可以正常加载,也可以通过ajax actionlink加载. 如果我将Javascipt文件与部分视图一起放入,则所有代码均按预期工作,但是脚本多次加载(因此,使用户下载更多脚本,由于某种原因,它们也不被缓存).

My entire website is an Ajax website, so all of my views (apart from Layout) can either be loaded normally or via an ajax actionlink. If I put the Javascipt files in with the partial views then all of the code works as expected, but the scripts get loaded multiple times (thus making the user download more scripts, all of them aren't being cached for some reason either).

如果我将脚本文件放入布局"中,则它们只会被加载一次,但是如果加载了部分视图,则该部分视图的JS代码显然无法正常工作,因为脚本已在部分视图时加载没有呈现.

If I put the script files in my Layout, then they only get loaded once but if a partial view gets loaded then the JS code for that partial view doesn't work obviously, because the scripts were already loaded when the partial view wasn't rendered.

我的问题是,如何才能使脚本仅加载一次,又如何以某种方式影响脚本的局部视图?

My question is, how can I make the scripts get loaded only once, but also somehow have them affect partial views?

索引视图:

<script src="/Scripts/Build/module.min.js"></script>
<script src="/Scripts/Build/upload-index.min.js"></script>

布局:

<li>
    @Ajax.ActionLink("Upload", "Index", "Upload", new {Area = "Music"}, new AjaxOptions {HttpMethod = "GET", UpdateTargetId = "body-wrapper", InsertionMode = InsertionMode.Replace, OnSuccess = "updateHistory", AllowCache = true }, new {@class = "nav-link"})
</li>

如果脚本在部分视图中,则可以看到它们多次加载:

You can see the scripts getting loaded multiple times if they are in the partial view:

推荐答案

脚本不应位于局部视图中,而应位于主视图或其布局中.您不仅会发现自己的身份重复问题,还会导致其他问题,例如使现有脚本无效.

Scripts should not be in partial views, only the main view or its layout. Not only do you have the duplicate issue you have identified your self, but it can lead to other issues such as invalidating existing scripts.

如果需要处理与动态添加的项目关联的事件,请使用.on()函数使用事件委托.例如

If you need to handle events associated with dynamically added items then use event delegation using the .on() function. For example

$.(container).on('click', '.someclass', function() { .... }

将处理具有class="someclass"的元素的click事件,这些元素已添加为container的子元素,即使它们是在最初加载DOM之后添加的.

will handle the click event of elements with class="someclass" that have been added as a child element of container even if they are added after the DOM has been initially loaded.

例如,如果您需要将插件附加到动态添加的元素上,则在将元素添加到DOM之后附加它,例如

If you need to attach a plugin to dynamically added elements, then attach it after the element has been added to the DOM, for example

$.get(url, function(html) {
    $(container).append(html); // append the partial view
    $(container).find('someclass:last')..dropzone({ .... }); // attach plugin
});

这篇关于ASP.NET MVC在局部视图中加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆