简体   繁体   English

如何有条件地加载JavaScript

[英]How to load JavaScript conditionally

Is there any way to conditionally load JavaScript reference files in ASP.Net Razor View? 有什么方法可以有条件地在ASP.Net Razor View中加载JavaScript参考文件吗? There are 15 web pages in my project. 我的项目中有15个网页。 They refer to common set of libraries say A, B, C, D. However, there is one page which require library E instead of B. 他们指的是一组通用的库,例如A,B,C,D。但是,有一个页面需要库E而不是B。

How can I write the tags so that it will load library E only for that particular page? 如何编写标签,以便仅将标签加载到该特定页面? And also it will NOT LOAD B for the same page? 而且它不会为同一页面加载B吗?

If I load E and B both, then the page crashes. 如果同时加载E和B,则页面崩溃。

You can set some flag, such as 您可以设置一些标志,例如

public ActionResult Index()
{
    ViewBag.Script = "B";
    return View();
}

and on your view 在你看来

if ((ViewBag.Script as string) == "B")
{
}
else
{
}

You can use @section, but then you couldn't include all scripts on the _Layout 您可以使用@section,但是不能在_Layout上包含所有脚本

在布局视图上渲染

视图部分

ASP.NET MVC 3: Layouts and Sections with Razor ASP.NET MVC 3:带有Razor的布局和节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM